Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 984
William Yeung Avatar asked Dec 03 '08 10:12

William Yeung


4 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']
like image 171
nicholaides Avatar answered Nov 20 '22 09:11

nicholaides


Rails has JSON support built in:

def json_response
    ActiveSupport::JSON.decode @response.body
end

No need for a plugin

Then you can do something like this:

assert_equal "Mike", json_response['name']
like image 31
Josh Avatar answered Nov 20 '22 07:11

Josh


If you are using RSpec, json_spec is worth a look

https://github.com/collectiveidea/json_spec

like image 7
acw Avatar answered Nov 20 '22 08:11

acw


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
like image 4
Eric Avatar answered Nov 20 '22 07:11

Eric