2013-08-06 31 views
7

我正在開發一個使用rails 4的rails API,並且我想測試它。要做到這一點,我正在使用Rspec框架。Rails中的Rspec授權

我的API有被稱爲像這樣的身份驗證方法:

class UsersController < ApplicationController 
# Token authentication 
before_action :set_user, except: [:index, :create] 
before_action :authenticate, except: [:index, :create] 
before_action :authenticate_admin, only: [:index, :create] 

... 
end 

然後,我有我的UsersController Rspec的:

describe UsersController do 
render_views 
describe "GET /users" do 
    it "gets all users" do 
    @request.env["AUTHORIZATION"] = "Token token=xxxxxxxxx" 
    @request.env["HTTP_ACCEPT"] = "application/json" 
    @request.env["CONTENT_TYPE"] = "application/json" 
    get :index 
    response.status.should be(200) 
    end 
end 
end 

當我執行的測試中,它給了我總是相同的:

UsersController GET /users getting all users 
Failure/Error: response.status.should be(200) 

    expected #<Fixnum:401> => 200 
     got #<Fixnum:803> => 401 
... 

我使用authenticate_or_request_with_http_token方法從heade獲取令牌RS。

如果任何人都可以幫助我找到跳過before_action方法或正確設置Authentication標頭的方法,我將非常感激。

謝謝!

+0

我們將需要看到我認爲進行身份驗證的身份驗證方法。或者,也許你正在使用設計或類似?有一件事要檢查:你似乎沒有這樣做:在索引上進行身份驗證(這是你正在測試的)。 –

+0

謝謝你的評論傑西。我複製了代碼,但我忘記複製索引的身份驗證方法,即: before_action:authenticate_admin,only:[:index,:create] 我使用authenticate_or_request_with_http_token進行身份驗證。 謝謝。 – jmolina

+0

我仍然需要查看您的身份驗證方法。它將採用令牌,併爲您的current_user執行查找,對嗎?另外,您是否在規格設置期間使用您的令牌創建用戶? –

回答

9

我終於解決了這個問題。

的錯誤是:

request.env["AUTHORIZATION"] 

必須

request.env["HTTP_AUTHORIZATION"]. 

除此之外,我從沒有在我的測試環境中創建的用戶得到一個錯誤的令牌。

:)