2013-10-17 99 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