How to check for a JSON response using RSpec?

json, rspec, ruby-on-rails

Solution

You can examine the response object and verify that it contains the expected value:

@expected = { 
        :flashcard  => @flashcard,
        :lesson     => @lesson,
        :success    => true
}.to_json
get :action # replace with action name / params as necessary
response.body.should == @expected

EDIT

Changing this to a `post` makes it a bit trickier. Here's a way to handle it:

 it "responds with JSON" do
    my_model = stub_model(MyModel,:save=>true)
    MyModel.stub(:new).with({'these' => 'params'}) { my_model }
    post :create, :my_model => {'these' => 'params'}, :format => :json
    response.body.should == my_model.to_json
  end

Note that `mock_model` will not respond to `to_json`, so either `stub_model` or a real model instance is needed.

Problem

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?

Original source