2011-04-25 49 views
0

我正在測試我的employees_controller,並且在我的索引測試中登錄用戶,我收到一個似乎與我的模型關係相關的錯誤。Rspec錯誤 - 當前用戶和另一個模型之間的關係

測試是:

describe "for signed-in user" do 
    before(:each) do 
    @user = test_sign_in(Factory(:user)) 
    end 

    it "should have the right title" do 
    get :index 
    response.should have_selector('title', :content => "Employee List") 
    end 

我有render_views集。我也讓每個用戶綁定到一個位置,員工索引視圖應該向員工顯示用戶的位置。而在我的索引視圖,我有以下的代碼以顯示員工的位置的名稱:

<h1>Listing employees for <%= current_user.location.name %> </h1> 

當我運行我的測試,我得到一個包含 「::的ActionView模板的錯誤消息::錯誤: 未定義方法的名稱爲零:NilClass「

在我的factories.rb文件中,我確實將用戶的位置ID設置爲有效的ID。爲什麼current_user.location返回零?我在測試中錯過了什麼?謝謝!

回答

2

很可能,只是登錄過程不正確。這是我如何做到的。我有一個/spec/support/controller_macros.rb和內:

module ControllerMacros 
    def login_user 
    before(:each) do 
     @request.env["devise.mapping"] = :user 
     @user = Factory(:user) 
     sign_in @user 
    end 
    end 
end 

現在,在我的控制器規格:

describe AbilitiesController do 
    login_user 

    describe "POST 'train' ..." do 
    ... 
    end 
... 
+0

我確實有一個規範的輔助文件登錄宏。在你的login_user宏中,@ request.env [「devise.mapping」] =:user做什麼? – NicSlim 2011-04-27 02:16:09

+0

我真的不知道它在做什麼(我真的不在乎),但官方設計wiki是如何使用它的。 – Spyros 2011-04-27 19:39:02

相關問題