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

时间:2011-11-03 16:33:11

标签: ruby-on-rails rspec rspec2 rspec-rails

在我的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)会被取消注册。

2 个答案:

答案 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)

相关问题