Ruby on rails 存根帮助器规范中的控制器帮助器方法

Ruby on rails 存根帮助器规范中的控制器帮助器方法,ruby-on-rails,rspec,rspec2,rspec-rails,Ruby On Rails,Rspec,Rspec2,Rspec Rails,在我的应用程序\u controller.rb中: helper_method :current_brand def current_brand @brand ||= Brand.find_by_organization_id(current_user.organization_id) end 在我的助手something\u helper.rb def brands return [] unless can? :read, Brand # current_brand is cal

在我的
应用程序\u controller.rb
中:

helper_method :current_brand
def current_brand
  @brand ||= Brand.find_by_organization_id(current_user.organization_id)
end
在我的助手
something\u helper.rb

def brands
  return [] unless can? :read, Brand
  # current_brand is called
end
我正在为
something\u helper
编写一份规范,并希望将
当前的\u品牌

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
导致<代码>名称错误: #的未定义局部变量或方法“当前#品牌”


我试过做
存根打开
self
controller
。奇怪的是,当我在
self
上存根时,
helper.stub!(:can?)。并且返回(true)
被取消注册。

您是否尝试过类似的操作:


ApplicationController.stub!(:当前品牌)和返回(品牌)

好的,再来点别的怎么样。。。你真的在问Brand.for_用户

因此:

然后,你只需:

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

或者类似的东西。。。如果你把这种逻辑提取出来,让它变得简单易懂。可能是Presenter类,也可能是此静态方法。

看起来
#current_brand
不是助手上的方法,而是控制器中的方法。你能把这个方法移到SomethingHelper中吗?Jesse,我可以,但我不想,因为控制器和视图都使用当前品牌。当助手上直接定义了
#当前_品牌
时,测试通过。当前_品牌做什么?它需要什么样的投入才能做出决定?我更新了问题,将实施纳入其中。它只返回属于用户的品牌。通常我会直接在用户上使用这个方法(
user#brand
),但这两个方法在不同的引擎中,存储在不同的数据库中。是的,这可能就是我最终要做的。我喜欢它作为控制器助手的一点是,它的作用域由请求确定。所以我可以拥有@current_品牌,并且只查找一次。当然,我也可以用静态方法来实现这一点,但它没有那么干净。在接受这个问题之前,我会把这个问题留长一点。你仍然可以这样做,用新的方法代替目前的品牌
def current_brand@brand | |=brand。对于_user(current_user)end
我最终为用户模型创建了一个mixin,因此我可以直接调用current_user.brand。谢谢你让我走上了正确的道路!
brand = mock(Brand)
Brand.stub(:for_user => brand)