2012-11-06 63 views
4

我有一個我正在開發的示例Rails應用程序,所以我可以開始熟悉BDD。使用Devise和RSpec測試身份驗證重定向

現在我正在使用Devise來處理我的用戶身份驗證。

我有一個任務模型,它需要用戶登錄才能訪問新的,創建,編輯和銷燬操作。

我有以下代碼:

請求/ tasks_spec.rb

describe "Tasks" do 

    it "redirects to sign in for new task if no user logged in" do 
    visit new_task_path 
    response.should redirect_to(new_user_session_path) 
    end 

end 

現在,當我運行這個測試,我希望它失敗,因爲我還沒有添加任何的before_filter邏輯TasksController。我運行測試,失敗。

現在我添加由Devise提供的authenticate_user!幫手。

tasks_controller.rb

class TasksController < ApplicationController 
    before_filter :authenticate_user!, only: [:new, :edit, :create, :destroy] 
    ... 
end 

的測試運行,並仍然失敗,說以下內容:

​​

現在要求訪問時,因爲沒有用戶建立會話,我期待該響應被重定向到/ user/sign_in。不過,我只是得到200OK回來。

缺少什麼我在這裏?我如何通過此測試?

回答

2

試試這個:

describe "redirects to sign in for new task if no user logged in" do 
    before { post tasks_path } 
    specify { response.should redirect_to(new_user_session_path) } 
end