2013-10-17 58 views
0

我正在尝试为我的API编写请求规范,但需要传递API密钥。 API密钥作为标题传递。在Web从我通过这样的:如何在需要API密钥时测试请求规范

Header: Authorization

Value: Token token="MyString"

在我的天赋,我想这样的:

describe "sessions" do 
    before do 
    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.authenti‌​cation_token}", {user: {name: "New Name"}}, { 'HTTP_AUTHORIZATION' => "Token token=\"MyString\"" } 
    response.status.should be(201) 
    end 
end 

这并不引发异常,但它也不起作用。我的测试只是失败,错误代码401

回答

0

的问题是一个简单的格式。我不得不添加一些日志记录来查看授权标题的发送方式。我刚才复制的输出,并与我的测试值替换的值,所以正确答案是:

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 

有一个问题,我发现同时添加记录。我之前有一个过滤器正在更改我的api_token,所以在发送调用之前,我的测试api_token的“秘密”被更改为真正的api_token。 Whops。所以道义是,写出测试值得花时间。

0

我相信标题散列应该是putget,post等相同)的第三个参数。在你的例子中,你将它作为第二个。

从文档:

put(path, parameters = nil, headers_or_env = nil) 

http://api.rubyonrails.org/classes/ActionDispatch/Integration/RequestHelpers.html#method-i-put

+0

我将它改为:'put“/api/v1/users/#{@user.id}?user_email=#{@user.email}&auth_token=#{@user.authenti cation_token}”,{user :{name:“New Name”}},{'HTTP_AUTHORIZATION'=>“Token token ='MyString'”}'但我在测试中仍然收到了'401'响应。 – Arel