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 に答える