title: How to pass authentication token in RSpec test for JSON API?
body: <p>I'm trying to add an authorization token to an RSpec <code>get</code> JSON API test in Rails. But everything tried so far results in an error. The issue seems that the token is not being properly passed in the request.</p>
  
  <pre><code>expected the response to have a success status code (2xx) but it was 401
  </code></pre>
  
  <p><strong>Current code:</strong></p>
  
  <p>Project_spec.rb (tests)</p>
  
  <pre><code>before do
      @project = create(:project, :key =&gt; "123")
      get '/api/v1/projects/1', {:Authorization =&gt; "Token 123"}, format: :json
  end
  
  it "returns correct status" do
      expect( response ).to have_http_status(:success)
  end
  </code></pre>
  
  <p>ProjectsController.rb</p>
  
  <pre><code>before_filter :restrict_access, :except =&gt; :create
  
  def show
      @project = Project.find(params[:id])
      render json: @project
  end
  
  def restrict_access
      authenticate_or_request_with_http_token do |token, options|
          Project.exists?(key: token)
      end
  end
  </code></pre>
  
  <p>Based on a few recommended solution found online, I've tried</p>
  
  <ol>
  <li><p><code>get '/api/v1/projects/1', format: :json, token: "123"</code></p></li>
  <li><p><code>get '/api/v1/projects/1', { 'HTTP-AUTHORIZATION' =&gt; 'Token "123"' }, format: :json</code></p></li>
  <li><p><code>get '/api/v1/projects/1', {:Authorization =&gt; "Token 123"}, format: :json</code></p></li>
  </ol>
  
  <p>But nothing seems to successfully pass the authorization token.</p>
  
  <p>Note: Style in #3 works when posting from an external application, but not in the RSpec test itself.</p>
  
  <p>Does anyone have experience with this and can share some direction?</p>