Using Rspec, how do I test the JSON format of my controller in Rails 3.0.11?
I realize that setting :format => :json
is one solution (as noted above). However, I wanted to test the same conditions that the clients to my API would use. My clients would not be setting the :format
parameter, instead they would be setting the Accept
HTTP header. If you are interested in this solution, here is what I used:
# api/v1/test_controller_spec.rbrequire 'spec_helper.rb'describe Api::V1::TestController do render_views context "when request sets accept => application/json" do it "should return successful response" do request.accept = "application/json" get :test response.should be_success end endend
Try moving the :format
key inside the params hash of the request, like this:
describe ApplicationsController do render_views disconnect_sunspot let(:application) { Factory.create(:application) } subject { application } context "JSON" do describe "creating a new application" do context "when not authorized" do it "should not allow creation of an application" do params = { :format => 'json', :application => { :name => "foo", :description => "bar" } } post :create, params Expect(Application.count).to eq(0) expect(response.status).to eq(403) expect(JSON.parse(response.body)["status"]).to eq("error") expect(JSON.parse(response.body)["message"]).to match(/authorized/) end end context "authorized" do end end endend
Let me know how it goes! thats the way I have set my tests, and they are working just fine!