I'm developing a rails API, using rails 4, and I want to test it. To do it, I am using Rspec framework.
My API has an authenticate method that is called like this:
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 my UsersController 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 execute the test, it gives me always the same:
UsersController GET /users getting all users
Failure/Error: response.status.should be(200)
expected #<Fixnum:401> => 200
got #<Fixnum:803> => 401
...
I use authenticate_or_request_with_http_token method to get token from headers.
If anyone can help me to find the method to skip before_action method or to set the Authentication header correctly I will be very grateful.
Thank you!
I finally solve the problem.
The error was that :
request.env["AUTHORIZATION"]
must be
request.env["HTTP_AUTHORIZATION"].
Apart from that, I was getting a wrong token from a user that was not created in my test environment.
:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With