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

前端 未结 2 1023
说谎
说谎 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
    

提交回复
热议问题