Rspec authorization in Rails

I am developing a rails API using rails 4 and I want to test it. For this, I use the Rspec infrastructure.

My API has an authentication method called as follows:

class UsersController < ApplicationController # Token authentication before_action :set_user, except: [:index, :create] before_action :authenticate, except: [:index, :create] before_action :authenticate_admin, only: [:index, :create] ... end 

Then I have UserController Rspec:

 describe UsersController do render_views describe "GET /users" do it "gets all users" do @request.env["AUTHORIZATION"] = "Token token=xxxxxxxxx" @request.env["HTTP_ACCEPT"] = "application/json" @request.env["CONTENT_TYPE"] = "application/json" get :index response.status.should be(200) end end end 

When I run the test, it always changes:

  UsersController GET /users getting all users Failure/Error: response.status.should be(200) expected #<Fixnum:401> => 200 got #<Fixnum:803> => 401 ... 

I use the authenticate_or_request_with_http_token method to get the token from the headers.

If anyone can help me find a way to skip the before_action method or set the authentication header correctly, I will be very grateful.

Thanks!

+7
ruby-on-rails rspec
source share
1 answer

I will finally solve the problem.

The error was as follows:

 request.env["AUTHORIZATION"] 

it should be

 request.env["HTTP_AUTHORIZATION"]. 

In addition, I received the wrong token from a user who was not created in my test environment.

:)

+9
source share

All Articles