问题描述
在我的 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
编写规范并希望存根 current_brand
I am writing a spec for something_helper
and wish to stub current_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:#<#<Class:0x000001068fd188>:0x0000010316f6f8>
我也尝试在 self
和 controller
上做 stub!
.奇怪的是,当我在 self
上存根时,helper.stub!(:can?).and_return(true)
被取消注册.
I have tried doing the stub!
on self
and controller
as well. Strangely, when I stub on self
, the helper.stub!(:can?).and_return(true)
gets unregistered.
推荐答案
好吧,其他的怎么样...你真的在问 Brand.for_user
OK, how about something else... You're really asking 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 类,或者这个静态方法.
Or something similar... If you extract that logic out to something that is easily stubbable, it'll make things easier. A Presenter class, perhaps, or this static method.
这篇关于在辅助规范中存根控制器辅助方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!