How to post JSON data in rails 3 functional test

前端 未结 7 1822
礼貌的吻别
礼貌的吻别 2021-02-04 06:55

I plan to use JSON data in both request and response in my project and having some problems in testing.

After searching for a while, I find the following code which uses

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-04 07:22

    Just specify appropriate content type:

    post :index, '{"foo":"bar", "bool":true}', "CONTENT_TYPE" => 'application/json'
    

    Json data should go as a string, not as a Hash. Looking at stack trace running a test you can acquire more control on request preparation: ActionDispatch::Integration::RequestHelpers.post => ActionDispatch::Integration::Session.process => Rack::Test::Session.env_for

    Specifying :format does not work because request go as 'application/x-www-form-urlencoded' and json isn't parsed properly processing a request body.

提交回复
热议问题