0

I have a Controller:

class ThingController < ActionController
  respond_to :json

  def create
    puts "CREATE " + params.inspect
  end
end

and a test:

require "spec_helper"

describe "/thing" do
  context "create" do
    it "should get params" do
      params = {"a" => "b", "c" => ["d"], "e" => [], "f"=>"",
                "g"=>nil, , "controller" => "NOPE", "action" => "NOPE"}
      post uri, params
    end
  end 
end

When I run this, the following is logged:

CREATE {"a"=>"b", "c"=>["d"], "action"=>"create", "controller"=>"thing"}

My questions are:

  • where did e go? I would expect it to deserialize to an empty array, not to nothing at all.
  • why are the action and controller params being mixed into this? Aren't the body and the rails internals completely separate concerns?
  • Because of this, my action and controller JSON fields were over-written. How would I access these?
  • Is this therefore not the right way to accept JSON?

I'm new to Rails, but I have done a lot of Django.

Joe
  • 46,419
  • 33
  • 155
  • 245

2 Answers2

0

The rails middleware will add the action and controller params so you'll have to put those in a nested hash if you still want to access your custom values.

Try adding format: 'json' to the params in your test. This will send a different content-type header and might help serialize the params correctly in order to keep the e param.

DiegoSalazar
  • 13,361
  • 2
  • 38
  • 55
0

There are two parts to this problem: you need to ensure that your parameters are being sent as JSON, and also that they are being interpreted as JSON.

Essentially, you have to

  • encode your parameters as JSON
  • set appropriate content-type and accepts headers

See POSTing raw JSON data with Rails 3.2.11 and RSpec for the way.

Community
  • 1
  • 1
Todd Agulnick
  • 1,945
  • 11
  • 10