Set Rspec default GET request format to JSON

前端 未结 10 1903
失恋的感觉
失恋的感觉 2020-12-02 22:31

I am doing functional tests for my controllers with Rspec. I have set my default response format in my router to JSON, so every request without a suffix will return JSON.

10条回答
  •  自闭症患者
    2020-12-02 22:49

    Running Rails 5 and Rspec 3.5 I had to set the headers to accomplish this.

    post '/users', {'body' => 'params'}, {'ACCEPT' => 'application/json'}
    

    Thi matches what the example in the docs looks like:

    require "rails_helper"
    
    RSpec.describe "Widget management", :type => :request do
      it "creates a Widget" do
        headers = {
          "ACCEPT" => "application/json",     # This is what Rails 4 accepts
          "HTTP_ACCEPT" => "application/json" # This is what Rails 3 accepts
        }
        post "/widgets", { :widget => {:name => "My Widget"} }, headers
    
        expect(response.content_type).to eq("application/json")
        expect(response).to have_http_status(:created)
      end
    end
    

提交回复
热议问题