在辅助规范中存储控制器辅助方法

在我的application_controller.rb

 helper_method :current_brand def current_brand @brand ||= Brand.find_by_organization_id(current_user.organization_id) end 

在我的帮助者something_helper.rb

 def brands return [] unless can? :read, Brand # current_brand is called end 

我正在为something_helper编写一个规范,并希望将stub_brand存根

 describe SomethingHelper do before :each do helper.stub!(:can?).and_return(true) # This stub works end it "does the extraordinary" do brand = Factory.create(:brand) helper.stub!(:current_brand).and_return(brand) # This stub doesnt work helper.brands.should_not be_empty end end 

NameError: undefined local variable or method 'current_brand' for #<#:0x0000010316f6f8>结果NameError: undefined local variable or method 'current_brand' for #<#:0x0000010316f6f8>

我试过做stub!selfcontroller上也是如此。 奇怪的是,当我self存根时, helper.stub!(:can?).and_return(true)被取消注册。

好吧,别的怎么样……你真的在问Brand.for_user

所以:

 class Brand ... def self.for_user(user) find_by_organization_id(user.organization_id) end end 

然后,你只是:

 brand = mock(Brand) Brand.stub(:for_user => brand) 

或者类似的东西……如果你把这个逻辑提取到容易潦倒的东西,它会让事情变得更容易。 也许是Presenter类,或者这个静态方法。

你尝试过类似的东西:

ApplicationController.stub!(:current_brand).and_return(brand)