How to check for a JSON response using RSpec?

Fizz picture Fizz · Mar 1, 2011 · Viewed 161.6k times · Source

I have the following code in my controller:

format.json { render :json => { 
        :flashcard  => @flashcard,
        :lesson     => @lesson,
        :success    => true
} 

In my RSpec controller test I want to verify that a certain scenario does receive a success json response so I had the following line:

controller.should_receive(:render).with(hash_including(:success => true))

Although when I run my tests I get the following error:

Failure/Error: controller.should_receive(:render).with(hash_including(:success => false))
 (#<AnnoController:0x00000002de0560>).render(hash_including(:success=>false))
     expected: 1 time
     received: 0 times

Am I checking the response incorrectly?

Answer

brentmc79 picture brentmc79 · Mar 7, 2011

You could parse the response body like this:

parsed_body = JSON.parse(response.body)

Then you can make your assertions against that parsed content.

parsed_body["foo"].should == "bar"