Reputation: 1315
I have a helper which has some logic for controlling the display of a partial :
module BannerHelper
def show_add_friend_link?
!current_page(friends_path) && !current_user.has_friends?
end
end
require 'rails_helper'
describe BannerHelper do
context 'when user has friends'
it 'does not show the add friends link' do
expect(helper.show_add_friend_link?).to eq false
end
end
end
I'm trying to create a test (using rspec 3.2) but current_user isn't defined. I have been able to use current_user from controller tests. current_user is defined in application_controller. Perhaps current_user shouldn't be referred to from a helper though I am not sure where to place this logic.
Upvotes: 1
Views: 789
Reputation: 3928
I have solved this by abandoning RSpec's helper test features and instead testing helper modules within the controller test ecosystem. Doing so provides access to the request
and session
objects, as well as other helper methods.
Here is an example:
describe BannerHelper, type: :controller do
controller(ApplicationController) do
include BannerHelper
end
describe "#show_add_friend_link?" do
context 'when user has friends'
it 'does not show the add friends link' do
allow(subject).to receive(:current_user).and_return(some_user)
# note that instead of ^ mock you can also simply set needed session key as it is accessible.
expect(subject.send(:show_add_friend_link?)).to eq false
end
end
end
end
Upvotes: 0
Reputation: 176552
You have two options.
Since the RSpec group that described an Helper mixes the helper module into itself, you can define the current_user as method inside the example.
describe BannerHelper do
context 'when user has friends'
let(:current_user) { instance_double("User", has_friends: true) }
it 'does not show the add friends link' do
expect(show_add_friend_link?).to eq false
end
end
end
Use dependency injection, and change the helper method to accept the current_user
as parameter.
Upvotes: 2