JSON Rails API Functional Testing

I am currently creating a JSON API running on Rails / rails-api. I have a route that accepts JSON sending through a PATCH request and a filter before that needs access to the raw / JSON request .

For testing purposes, I added the following before the filter to show my problem:

before_filter do puts "Raw Post: #{request.raw_post.inspect}" puts "Params: #{params.inspect}" end 

The following curl request works as intended:

 curl -X PATCH -H "Content-Type: application/json" -d '{"key":"value"}' http://localhost:3000/update # Raw Post: "{\"key\":\"value\"}" # Params: {"key"=>"value", "action"=>"update", "controller"=>"posts"} 

However, I have not tested this method, none of the following calls work:

  • Params are included, but not as passed JSON

     test 'passing hash' do patch :update, { key: "value" } end # Raw Post: "key=value" # Params: {"key"=>"value", "controller"=>"posts", "action"=>"update"} 
  • Passwords are included, but again not as passed JSON

     test 'passing hash, setting the format' do patch :update, { key: "value" }, format: :json end # Raw Post: "key=value" # Params: {"key"=>"value", "controller"=>"posts", "action"=>"update", "format"=>"json"} 
  • JSON format but not included in parameters

     test 'passing JSON' do patch :update, { key: "value" }.to_json end # Raw Post: "{\"key\":\"value\"}" # Params: {"controller"=>"posts", "action"=>"update"} 
  • JSON format but not included in parameters

     test 'passing JSON, setting format' do patch :update, { key: "value" }.to_json, format: :json end # Raw Post: "{\"key\":\"value\"}" # Params: {"format"=>"json", "controller"=>"posts", "action"=>"update"} 

This list is even longer, I just wanted to show you my problem. I tested setting the Accept and Content-Type headers to application/json too, nothing seems to help. Am I doing something wrong, or is this a bug in Rails functional tests?

+6
source share
1 answer

This is a bug reported by the same author of this question. Most likely, it will not be fixed before Rails 5, or it seems that it will look at the stage to which it was assigned.

If you land here, like me, in a few hours, encountering this problem, not knowing that this is really a mistake, you might want to know that you can do this in the integration test:

$ rails g integration_test my_integration_test

 require 'test_helper' class MyIntegrationTestTest < ActionDispatch::IntegrationTest setup do @owner = Owner.create(name: 'My name') @json = { name: 'name', value: 'My new name' }.to_json end test "update owner passing json" do patch "/owners/#{@owner.id}", @json, { 'Accept' => Mime::JSON, 'Content-Type' => Mime::JSON.to_s} assert_response :success assert_equal 'application/json', response.headers['Content-Type'] assert_not_nil assigns :owner assert_equal 'My new name', assigns(:owner).name end end 
+6
source

Source: https://habr.com/ru/post/959165/


All Articles