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?

Answers


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

Here's the basic gist for a test:

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

Here's documentation for the gem: http://json.rubyforge.org/. Also, you can play with the JSON gem in IRB pretty easily.


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']

Need Your Help

iOS - pushViewController without sliding Background Image

ios objective-c uitableview uinavigationcontroller

Messing around with pushViewcontroller due to one of the awkward requirement :/