How to check for a JSON response using RSpec? How to check for a JSON response using RSpec? ruby-on-rails ruby-on-rails

How to check for a JSON response using RSpec?


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

@expected = {         :flashcard  => @flashcard,        :lesson     => @lesson,        :success    => true}.to_jsonget :action # replace with action name / params as necessaryresponse.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.


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"


Building off of Kevin Trowbridge's answer

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