Using Rspec, how do I test the JSON format of my controller in Rails 3.0.11?

前端 未结 2 1001
说谎
说谎 2020-12-24 04:57

I\'ve scoured the web, but, alas, I just can\'t seem to get Rspec to correctly send content-type so I can test my JSON API. I\'m using the RABL gem for templates, Rails 3.0.

相关标签:
2条回答
  • 2020-12-24 05:16

    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.rb
    require '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
      end
    end
    
    0 讨论(0)
  • 2020-12-24 05:22

    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
      end
    end
    

    Let me know how it goes! thats the way I have set my tests, and they are working just fine!

    0 讨论(0)
提交回复
热议问题