How to test JSON result from Ruby on Rails functional tests?

Viewed 40514

How can I assert my Ajax request and test the JSON output from Ruby on Rails functional tests?

9 Answers

In Rails >= 5

Use ActionDispatch::TestResponse#parsed_body.

Example:

user = @response.parsed_body
assert_equal "Mike", user['name']

In Rails up to 4.x

Use JSON.parse, which takes a string as input and returns a Ruby hash that the JSON represents.

Example:

user = JSON.parse(@response.body)
assert_equal "Mike", user['name']

Also for short JSON responses you can simply match a string of the JSON to @response.body. This prevents having to rely on yet another gem.

assert_equal '{"total_votes":1}', @response.body

In newer versions of rails, you can leverage parsed_body to get access to this in your tests without any work.

Calling parsed_body on the response parses the response body based on the last response MIME type.

Out of the box, only :json is supported. But for any custom MIME types you've registered, you can add your own encoders...

https://api.rubyonrails.org/v5.2.1/classes/ActionDispatch/IntegrationTest.html

Related