In Rails 4 (at least in 4.2.11.3) there's no easy way to test your controllers that consume json (functional tests). For parsing json in a running server the ActionDispatch::ParamsParser
middleware is responsible. Controller tests though rely on Rack, which can't parse json to this day (not that it should).
You can do:
post :create, body_params.to_json
or:
post :update, body_parmas.to_json, url_params
But body_params
won't be accessible in the controller via params
. You've got to do JSON.parse(request.body.read)
. So the only thing that comes to mind is:
post :update, url_params.merge(body_params)
That is, in tests pass everything via parameters (application/x-www-form-urlencoded
). In production the body will be parsed by ActionDispatch::ParamsParser
to the same effect. Except that your numbers become strings (and possibly more):
# test/controllers/post_controller_test.rb
post :update, {id: 1, n: 2}
# app/controller/posts_controller.rb
def update
p params # tests:
# {"id"=>"1", "n" => "2", "controller"=>"posts", "action"=>"update"}
# production
# {"id"=>"1", "n" => 2, "controller"=>"posts", "action"=>"update"}
end
If you're willing to parse json in controllers yourself though you can do:
# test/controllers/post_controller_test.rb
post_json :update, {n: 2}.to_json, {id: 1}
# app/controller/posts_controller.rb
def update
p JSON.parse(request.body.read) # {"id"=>"1", "n" => 2, "controller"=>"posts", "action"=>"update"}
end
body
parameter. This is the best way to do it in Rails 5 and Rails 6.