Lets say I have the following code on ApplicationController :
class ApplicationController < ActionController::Base
helper_method :is_happy?
private
def is_happy?
true
end
end
and then, on my ApplicationHelper I have a method, which I would like to test like this:
def show_mood_text
return 'Happy' if is_happy?
'Sad'
end
I would like to test both cases, when is_happy? returns true and when it returns false . So, my option was to stub is_happy? method. For that, I did the following:
it 'returns Sad when when is sad' do
allow(helper).to receive(:is_happy?).and_return(false)
expect(helper.show_mood_text).to eq "Sad"
end
But when I try to run this test, I got the following error:
Failure/Error: allow(helper).to receive(:is_happy?).and_return(false)
#<ActionView::Base:0x00000000009e70> does not implement: is_happy?
You can just define the method in your spec file. The RSpec DSL is creating classes behind the scenes and your helper module is just mixed into those classes. Since you want both possible answers you can use the context to create different classes with different answers. So:
describe ApplicationHelper, type: :helper do
describe 'mood text' do
context 'happy' do
it 'returns "Happy" text' do
expect( show_mood_text ).to eq 'Happy'
end
def is_happy? = true
end
context 'sad' do
it 'returns "Sad" text' do
expect( show_mood_text ).to eq 'Sad'
end
def is_happy? = false
end
end
end
I haven’t run the above but I believe it should work. No rspec mocking needed.
Some side style issues. Just advice so ignore if you like it your way.
Just name the method happy?. In Ruby the is_ prefix is generally not used as the ? suffix implies a boolean response.
show_mood_text might be better named just mood_text