I need some help with testing the following. I am doing the RailsCast about securing an api: http://railscasts.com/episodes/352-securing-an-api?view=asciicast
I have a RequestController
with a before_filter
to check if the request has a token:
class RequestsController < ApplicationController
include ActionController::MimeResponds
include ActionController::HttpAuthentication::Token::ControllerMethods
before_filter :restrict_access
respond_to :json
#...
def authenticate
return restrict_access
end
private
def restrict_access
authenticate_or_request_with_http_token do |token, options|
ApiKey.exists?(access_token: token)
end
end
end
My failing rspec test looks like:
it 'responds successfully to generic request because of key protection' do
api_key = ApiKey.create
api_key.save!
get :index
request.headers["token"] = api_key.access_token
expect(response).to be_success # test for the 200 status-code
end
with result: expected success? to return true, got false
I don't understand how I can inject the valid api_key in to the request so that the response will evaluate to true. Any ideas? Thanks.
Token Authentication expects a HTTP_AUTHORIZATION
header in this format:
Token token="my-api-token"
Also, you'll want to set the header before the get :index
line:
request.headers["HTTP_AUTHORIZATION"] = "Token token=\"#{api_key.access_token}\""
get :index
You can use the encode_credentials
method instead if you prefer:
request.headers["HTTP_AUTHORIZATION"] = ActionController::HttpAuthentication::Token.encode_credentials(api_key.access_token)
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