How to check for a JSON response using RSpec?

后端 未结 14 1280
谎友^
谎友^ 2020-11-29 16:03

I have the following code in my controller:

format.json { render :json => { 
        :flashcard  => @flashcard,
        :lesson     => @lesson,
             


        
14条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 16:32

    You can also define a helper function inside spec/support/

    module ApiHelpers
      def json_body
        JSON.parse(response.body)
      end
    end
    
    RSpec.configure do |config| 
      config.include ApiHelpers, type: :request
    end
    

    and use json_body whenever you need to access the JSON response.

    For example, inside your request spec you can use it directly

    context 'when the request contains an authentication header' do
      it 'should return the user info' do
        user  = create(:user)
        get URL, headers: authenticated_header(user)
    
        expect(response).to have_http_status(:ok)
        expect(response.content_type).to eq('application/vnd.api+json')
        expect(json_body["data"]["attributes"]["email"]).to eq(user.email)
        expect(json_body["data"]["attributes"]["name"]).to eq(user.name)
      end
    end
    

提交回复
热议问题