How to stub a function IN a Helper during test

旧时模样 提交于 2020-01-04 05:31:07

问题


Take a look at this helper function:

def show_welcome_banner?
  (controller_name == 'competition' && action_name == 'index') ||
  (controller_name == 'submissions' && action_name == 'show')
end

It expects the controller_name and action_name functions to be defined.

I tried to use this in my RSpec matcher:

describe PageHelper do
  it "should know when the welcome banner is to be shown" do
    helper.stub!(:controller_name).and_return('index')
    show_welcome_banner?.should == false
  end
end

But this won't really work.

How could I stub the functions INSIDE the helper? Perhaps using instance_eval? Thanks!

EDIT, tried to use

controller.stub!(:controller_name).and_return('index')

but got

  1) PageHelper should know when the welcome banner is to be shown
     Failure/Error: show_welcome_banner?.should == false
     NameError:
       undefined local variable or method `controller_name' for #<RSpec::Core::ExampleGroup::Nested_1:0x1059a10b8>
     # ./app/helpers/page_helper.rb:16:in `show_welcome_banner?'
     # ./spec/helpers/page_helper_spec.rb:7

The helper is put in spec/helper/page_helper_spec.rb..


回答1:


Have you tried

stub!(:controller_name).and_return('index')

Seems to have worked for me :)




回答2:


Have you tried something like this in your Rspec?

controller.stub!(:controller_name).and_return('index')

The helpers are just modules that get included in ApplicationController. I believe that method comes from ActionController::Base.




回答3:


rspec-rails 3.5

allow(helper).to receive(:controller_name) { 'submissions' }


来源:https://stackoverflow.com/questions/5927132/how-to-stub-a-function-in-a-helper-during-test

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