Заглушить вспомогательный метод контроллера в спецификации помощника - PullRequest
0 голосов
/ 03 ноября 2011

В моем 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 ]

1 голос
/ 04 ноября 2011

Хорошо, а как насчет чего-то еще? Вы действительно спрашиваете 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 или этот статический метод.

0 голосов
/ 04 ноября 2011

Вы пробовали что-то похожее на:

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

...