How to stub a function IN a Helper during test
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..
Have you tried
stub!(:controller_name).and_return('index')
Seems to have worked for me :)
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
.
rspec-rails 3.5
allow(helper).to receive(:controller_name) { 'submissions' }
精彩评论