Stub a controller helper method in a helper spec

萝らか妹 提交于 2019-12-12 02:46:48

问题


In my application_controller.rb:

helper_method :current_brand
def current_brand
  @brand ||= Brand.find_by_organization_id(current_user.organization_id)
end

In my helper something_helper.rb

def brands
  return [] unless can? :read, Brand
  # current_brand is called
end

I am writing a spec for something_helper and wish to stub 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

Results in NameError: undefined local variable or method 'current_brand' for #<#<Class:0x000001068fd188>:0x0000010316f6f8>

I have tried doing the stub! on self and controller as well. Strangely, when I stub on self, the helper.stub!(:can?).and_return(true) gets unregistered.


回答1:


OK, how about something else... You're really asking Brand.for_user

So:

class Brand
  ...
  def self.for_user(user)
    find_by_organization_id(user.organization_id)
  end
end

Then, you'd just:

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

Or something similar... If you extract that logic out to something that is easily stubbable, it'll make things easier. A Presenter class, perhaps, or this static method.




回答2:


Have you tried something similar to:

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



来源:https://stackoverflow.com/questions/7998491/stub-a-controller-helper-method-in-a-helper-spec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!