title: Set header in RSpec 3 request
body: <p>I'm trying to set the header for some RSpec requests that require authentication. The header is <code>ACCESS_TOKEN</code>. No matter how I attempt to set the header, it never gets set. I know the app works because I can manually test it, I just cant get rspec tests to work. See the full source code &amp; tests for this problem here: <a href="https://github.com/lightswitch05/rspec-set-header-example">https://github.com/lightswitch05/rspec-set-header-example</a></p>
  
  <p>Since authentication is used in most of my request specs, I've created support helper module to retrieve an access token and set it in the header. Below is the summary of how I'm trying to set the header, see everything I've tried in the <a href="https://github.com/lightswitch05/rspec-set-header-example/blob/master/spec/support/session_helper.rb">full source</a></p>
  
  <pre><code># my_app/spec/support/session_helper.rb
  module SessionHelper
    def retrieve_access_token
      post api_v1_session_path({email: 'test@example.com', password: 'poor_password'})
  
      expect(response.response_code).to eq 201
      expect(response.body).to match(/"access_token":".{20}"/)
      parsed = JSON(response.body)
      token = parsed['access_token']['access_token']
  
      @request.headers['HTTP_ACCESS_TOKEN'] = token
    end
  end
  </code></pre>
  
  <p>an example request spec that uses this helper and should work, but always fails because the header never gets set:</p>
  
  <pre><code># my_app/spec/requests/posts_spec.rb
  # ...
  context "create" do
    it "creates a post" do
      retrieve_access_token
      post = FactoryGirl.build(:post)
  
      post api_v1_posts_path(
        post: {
          title: post.title,
          content: post.content
        }
      )
  
      expect(response.body).to include('"id":')
      expect(response.body).to include('"title":"' + post.title + '"')
      expect(response.body).to include('"content":"' + post.content + '"')
      expect(response.response_code).to eq 201
    end
  end
  </code></pre>
  
  <p>I know I can manually set the header in the individual <code>get</code> and <code>post</code> requests - but that is not a maintainable solution for API-wide authorization. Imagine having to change every test if the header name changed slightly. </p>