2013-10-18 88 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

相關問題