views:

2233

answers:

4

As title, I want to assert my AJAX request and test the JSON output, how can I do that?

+7  A: 

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(@request.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.

nicholaides
+3  A: 

@request.body ought to be @response.body

Other than that, nicholaides answer worked for me.

+2  A: 

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
Eric
+5  A: 

Rails has JSON support built in:

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

No need for a plugin

Josh