RSpec Request - How to set http authorization header for all requests

后端 未结 4 2165
清歌不尽
清歌不尽 2021-02-07 06:01

I\'m using rspec request to test a JSON API that requires an api-key in the header of each request.

I know I can do this:

get \"/v1/users/janedoe.json\"         


        
4条回答
  •  抹茶落季
    2021-02-07 06:15

    I don't think you should depend on the header if you are not testing the header itself, you should stub the method that checks if the HTTP_AUTORIZATION is present and make it return true for all specs except the spec that tests that particular header

    something like... on the controller

    Controller...
      before_filter :require_http_autorization_token
    
      methods....
    
      protected
      def require_http_autorization_token
        something
      end
    

    on the spec

    before(:each) do
      controller.stub!(:require_http_autorization_token => true)
    end
    
    describe 'GET user' do
      it 'returns something' do
        #call the action without the auth token
      end
    
      it 'requires an http_autorization_token' do
        controller.unstub(:require_http_autorization_token)
        #test that the actions require that token
      end
    end
    

    that way one can forget the token and test what you really want to test

提交回复
热议问题