在我的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
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 #<#<Class:0x000001068fd188>:0x0000010316f6f8>
我已尝试在stub!
和self
上执行controller
。奇怪的是,当我在self
上存根时,helper.stub!(:can?).and_return(true)
会被取消注册。
答案 0 :(得分:1)
好的,别的怎么样......你真的在问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类,或者这种静态方法。
答案 1 :(得分:0)
您是否尝试过类似的内容:
ApplicationController.stub!(:current_brand).and_return(brand)