Reputation: 3938
I can't find anything on this. How do I pass an API key in my RSpec request tests?
My API Key is sent in a header, so I pass it like this in the web:
Header: Authorization
Value: Token token="c32a29a71ca5953180c0a60c7d68ed9e"
How do I pass it in an RSpec request spec?
Thanks!!
Edit:
Here is my spec:
require 'spec_helper'
describe "sessions" do
before do
@program =FactoryGirl.create(:program)
@user = FactoryGirl.create(:user)
FactoryGirl.create(:api_key)
end
it "is authenticated with a token" do
put "/api/v1/users/#{@user.id}?user_email=#{@user.email}&auth_token=#{@user.authentication_token}", {user: {name: "New Name"}}, { 'Authorization' => "Token token='MyString'" }
response.status.should be(201)
end
it "fails without an API Token" do
put "/api/v1/users/#{@user.id}?user_email=#{@user.email}&auth_token=#{@user.authentication_token}", user: {name: "New Name"}
response.status.should be(401)
end
end
Upvotes: 4
Views: 2486
Reputation: 3938
So I was very close. I needed to log the output from making an actual API call to see what the exact format the server was expecting for the HTTP Header. So, the problem was that the format was a little off.
describe "sessions" do
before do
@user = FactoryGirl.create(:user)
@api_key = FactoryGirl.create(:api_key)
end
it "is authenticated with a token" do
put "/api/v1/users/#{@user.id}?user_email=#{@user.email}&auth_token=#{@user.authentication_token}", {user: {name: "New Name"}}, { "HTTP_AUTHORIZATION"=>"Token token=\"#{@api_key.access_token}\"" }
response.status.should be(201)
end
end
As you can see I had to change the format from : { 'Authorization' => "Token token='MyString'" }
to { "HTTP_AUTHORIZATION"=>"Token token=\"#{@api_key.access_token}\"" }
I also just replaced 'MyString'
with the more robust reference to the actual instance of the api token. @api_key.access_token
Upvotes: 5