Reputation: 643
I have an "Add friend" button in user profile pages (users#show) and I want to test that the button does not show up on your own profile page (current_user's)
I have this in the view file (users/show.html.haml):
- unless current_user == params[:id]
= button_to 'Add friend', path
I want to create a helper for it in UsersHelper
:
module UsersHelper
def correct_user
current_user == params[:id]
end
end
So in the view it would be:
- unless correct_user
= button_to 'Add friend', path
How do I test this in RSpec?
In my spec/helpers/users_helper_spec.rb
file I have:
it 'checks correct user' do
sign_in( user = create(:user) )
user2 = create(:user, name: 'foobar')
get :show, params: { id: user2.to_param }
expect(helper.correct_user).to be true
end
I have this for the sign_in
(current_user) Devise helper that signs in the user:
RSpec.configure do |config|
config.include Devise::Test::ControllerHelpers, type: :helper
end
Basically the test fails because doing get :show, params: { id: user2.to_param }
is giving me an error and gives me the impression that routing is not possible in helper specs.
How do I go about testing correct_user
helper? Should I just move it to the controller (so I can do get :show, params: { id: user2.to_param }
in the spec) and test it there? (and just make it a helper method helper_method :correct_user
)
Upvotes: 1
Views: 526
Reputation: 4920
You should not be using params[:id]
to check if user
matches current_user
. You must have fetched the User
with params[:id]
in your controller action. Say, you stored it in a variable @user
. Then, you can modify your helper and view like this:
Helper:
module UsersHelper
def can_add_friend?(user)
current_user != user
end
end
View:
- if can_add_friend?(@user)
= button_to 'Add friend', path
It would be easier to write rspec for this helper method now.
it 'checks correct user' do
sign_in( user = create(:user) )
user2 = create(:user, name: 'foobar')
expect(helper.can_add_friend?(user2)).to be true
expect(helper.can_add_friend?(user)).to be false
end
Upvotes: 1