Appending headers to Rspec controller tests

后端 未结 3 521
走了就别回头了
走了就别回头了 2021-02-05 15:35

I\'m trying to write out tests for a controller of mine that takes in requests from external services. So far this is my test:

describe ApplyController do
  cont         


        
相关标签:
3条回答
  • 2021-02-05 16:03

    Ok this is pretty silly of rspec.

    Custom headers in Request Specs

    headers = {
      'AUTH' => 'super secret key'
    }
    
    post '/api/some_action', { user_id: 1337 }.to_json, headers
    

    And in your controller:

    def some_action
      token = request.headers['AUTH']
    end
    

    Custom headers in Controller Specs

    headers = {
      'AUTH' => 'super secret key'
    }
    
    post '/api/some_action', { user_id: 1337 }, headers
    

    And in your controller:

    def some_action
      token = request.headers['rack.session']['AUTH']
    end
    

    Just sharing the differences I had between the two. I don't believe I have any special configuration in rspec or rails to have the two different spec types' headers to be placed differently.

    0 讨论(0)
  • 2021-02-05 16:10

    I think you want (straight from one of your links)

    it "returns 200 ok"
      @request.headers['X-Indeed-Signature'] = signature
      post :indeed, parameters
      response.status.should == 200
    end
    

    You don't need subject(:response)

    0 讨论(0)
  • 2021-02-05 16:11

    I was able to fix it by using @request.env instead of @request.headers like so:

    describe ApplyController do
      context 'when valid' do
        let(:parameters) do
          file = File.join File.dirname(__FILE__), '..', 'samples', 'Indeed.json'
          JSON.parse(File.read file)
        end
        let(:signature) { 'GC02UVj0d4bqa5peNFHdPQAZ2BI=' }
    
        it 'returns 200 ok if Request is valid' do
          @request.env['X-Indeed-Signature'] = signature
          post :indeed, parameters
          expect(response.status).to eq 200
        end
      end
    end
    
    0 讨论(0)
提交回复
热议问题