0

在我的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!这样selfcontroller。奇怪的是,当我存根时self,它helper.stub!(:can?).and_return(true)会被取消注册。

4

2 回答 2

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 类,也许,或者这个静态方法。

于 2011-11-03T21:08:42.010 回答
0

你有没有尝试过类似的东西:

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

于 2011-11-03T20:53:13.247 回答