2011-03-04 111 views
2

所以我只是試圖調用從用戶控制器log_in方法在RSpec中作爲Rspec的測試,呼叫控制器方法獲得NoMethodError

it "should get the index page" do 
    @user = User.new({ :email => "[email protected]" }) 
    log_in(@user) 
    get 'index' 
    response.should be_success 
end 

我得到的結果是一樣

1) EmployeesController GET 'index' should get the index page 
    Failure/Error: log_in(user) 
    NoMethodError: 
    undefined method `log_in' for #<RSpec::Core::ExampleGroup::Nested_1:0x4ac0328> 
    # ./spec/controllers/employees_controller_spec.rb:11:in `user_log_in' 
    # ./spec/controllers/employees_controller_spec.rb:16:in `block (2 levels) in <top (required)>' 

可有人幫幫我?由於

編輯2011年3月11日

這裏是log_in方法是在UserController的

def log_in(user) 
    session[:current_user] = user.id 
    end 
+0

你有沒有機會使用Devise? – raidfive 2011-03-05 07:23:56

+0

@raidfive不,我沒有使用Devise – Souloikj 2011-03-07 17:59:37

+0

方法'user_log_in'或'log_in'?你能包括這種方法嗎? – raidfive 2011-03-07 19:05:41

回答

13

如果你要撥打的控制器上的方法在一個RSpec控制器測試,你可以使用以下。

subject.send(:log_in,@user) 

它應該調用該方法。我不知道這是否是最佳做法。更好的方法是按照BurmajaM的建議存儲logged_in方法。

+0

'subject'是什麼?我知道我可以做'controller.send',所以我假設這就像'User.send(:log_in,@user)'? – Souloikj 2011-03-22 16:25:55

+0

不,它是主體,在這種情況下,它是控制器。 – Shiv 2011-03-22 16:44:42

5

你爲什麼不存根LOGGED_IN?或者你的方法是什麼。登錄不是這個規範的目標,所以存根!這是一個簡單的例子,我如何符合規範具有的before_filter控制器操作:

class MyController < ApplicationController 
    before_filter :logged_in? 

    def index 
    end 
end 



describe MyController do 
    describe "GET 'index'" do 
    context "when not logged in" 
     # you want to be sure that before_filter is executed 
     it "requires authentication" do 
     controller.expects :logged_in? 
     get 'index' 
     end 
     # you don't want to spec that it will redirect you to login_path 
     # because that spec belongs to #logged_in? method specs 
    end 
    context "when authenticated" do 
     before(:each) { controller.stubs :logged_in? } 
     it "renders :index template" do 
     get 'index' 
     should render_template(:index) 
     end 
     it "spec other things your action does when user is logged in" 
    end 
    end 
end 
+0

我嘗試使用存根,但是如果我在另一個控制器spec文件中,它似乎不起作用。在這種情況下,我在EmployeeController規範和調用UserController – Souloikj 2011-03-21 16:48:44

+0

嗯......這很奇怪!爲什麼在EmployeeController規範中調用UserController?它不必對#logged_in做任何事情?對? – BurmajaM 2011-03-23 14:15:01

+0

'@ BurmajaM'對於EmployeeController,有一個身份驗證檢查方式before_filter,我認爲我需要登錄才能通過這個before_filter – Souloikj 2011-03-29 21:12:25