Search code examples
ruby-on-railsjsonrspec-rails

How to pass authentication token in RSpec test for JSON API?


I'm trying to add an authorization token to an RSpec get 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.

expected the response to have a success status code (2xx) but it was 401

Current code:

Project_spec.rb (tests)

before do
    @project = create(:project, :key => "123")
    get '/api/v1/projects/1', {:Authorization => "Token 123"}, format: :json
end

it "returns correct status" do
    expect( response ).to have_http_status(:success)
end

ProjectsController.rb

before_filter :restrict_access, :except => :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

Based on a few recommended solution found online, I've tried

  1. get '/api/v1/projects/1', format: :json, token: "123"

  2. get '/api/v1/projects/1', { 'HTTP-AUTHORIZATION' => 'Token "123"' }, format: :json

  3. get '/api/v1/projects/1', {:Authorization => "Token 123"}, format: :json

But nothing seems to successfully pass the authorization token.

Note: Style in #3 works when posting from an external application, but not in the RSpec test itself.

Does anyone have experience with this and can share some direction?


Solution

  • Use it like:

     get '/api/v1/projects/1', {}, { Authorization:  "Token 123"}
    

    get is the http method, {} an empty params, { :Authorization => "Token 123"} headers

    get(path, parameters = nil, headers_or_env = nil)

    Documentation

    Other way:

    before do
        # some code here
        @request.env['Authorization'] = "Token 123"
        get '/api/v1/projects/1', format: :json
    end