How to check for a JSON response using RSpec?

Solution 1:

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"

Solution 2:

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.

Solution 3:

Building off of Kevin Trowbridge's answer

response.header['Content-Type'].should include 'application/json'

Solution 4:

There's also the json_spec gem, which is worth a look

https://github.com/collectiveidea/json_spec