2013-10-18 48 views
3

我在这找不到任何东西。我如何在RSpec请求测试中传递API密钥?使用API​​密钥的RSpec请求规格

我的API密钥是在标头中发送,所以我将它传递这样的网站:

Header: Authorization 
Value: Token token="c32a29a71ca5953180c0a60c7d68ed9e" 

我如何把它传递在一个RSpec要求规范?

谢谢!

编辑:

这里是我的规格:

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 
+0

你能分享你的规格吗?这取决于你如何称呼事情。 – muttonlamb

+0

当然可以!我刚刚发布了它们。第一个规范失败了,返回一个状态码“401” – Arel

回答

5

所以我是非常接近的。我需要记录来自进行实际API调用的输出,以查看服务器对HTTP头的预期格式。所以,问题在于格式有点偏离。

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 

正如你可以看到我不得不改变从格式:{ 'Authorization' => "Token token='MyString'" }{ "HTTP_AUTHORIZATION"=>"Token token=\"#{@api_key.access_token}\"" }

我也只是用更强大的参考API令牌的实际情况更换'MyString'@api_key.access_token

相关问题