2010-09-15 34 views
6

我試圖用rspec在我的current_user(使用修改後的restful_authentication auth解決方案)上剔除方法。我完全不確定如何在我的控制器規格中訪問此方法。 current_user本身不起作用。我需要首先獲得控制器嗎?我該怎麼做呢?RSpec訪問application_controller方法,如'current_user'

使用rails 2.3.5rspec 1.3.0rspec-rails 1.3.2

# my_controller_spec.rb 
require 'spec_helper' 

describe MyController do 

    let(:foos){ # some array of foos } 

    it "fetches foos of current user" do 
    current_user.should_receive(:foos).and_return(foos) 
    get :show 
    end 
end 

主要生產

NoMethodError in 'ChallengesController fetches foos of current user' 
undefined method `current_user' for #<Spec::Rails::Example::ControllerExampleGroup::Subclass_1::Subclass_1::Subclass_2::Subclass_2:0x7194b2f4> 

回答

2

RSpec的護欄給您控制器示例使用了controller方法。所以:

controller.stub!(:current_user).with(:foos).and_return(foos)

應該工作。

+0

真棒,我會測試此提到,順便說一句,什麼是'之間的區別stub'和'stub!' – brad 2010-09-16 12:26:30

+1

None - 'stub'是'stub!'的別名,所以它們可互換 – zetetic 2010-09-16 16:56:18

+0

工作! thx一堆 – brad 2010-09-21 14:32:09

0

我不完全熟悉restful_authentication,只是Authlogic和設計,但它可能在current_user類似的是一個控制器方法而不是一個對象,這就是爲什麼調用should_receive不按預期工作(你正在設定的對象的期望current_user返回,但該方法在期望範圍內無法訪問)。

試試這個:

stub!(:current_user).and_return(foos)

+0

我無法得到它噸,只是存根owork()我需要controller.stub以上 – brad 2010-09-21 14:32:26

1

它怎麼知道在哪裏可以找到current_user?這應該解決它:

subject.current_user.should_receive(:foos).and_return(foos) 
0

我讀了這個,並調整了我的一點。如果你只是想在用戶對象傳遞到您的Rspec的測試,您可以使用此:

  1. 首先,創建RSpec的測試中的用戶對象。例如:(使用任何屬性,你需要或需要創建用戶對象)

    用戶= User.create(名稱:「泰德」)

    (注:你也可以使用從工廠FactoryGirl)現在

  2. ,與被保存到變量 「用戶」,這樣做同樣的Rspec的測試範圍內的用戶對象:!

    controller.stub(:CURRENT_USER).and_return(用戶)

應該工作...

相關問題