I am trying to test that someone is able to login to my site by making a POST request to my SessionsController
. I've seen this way recommended in a few places:
it 'must be able to sign in a user' do
user = create(:user)
post :create, format: :js, user: {email: user.email, password: user.password, remember_me: 0}
assert_response :success
@controller.current_user.must_equal user
end
But this test is not correct. Calling @controller.current_user
will attempt to authenticate the user using the posted parameters and will return user
if the supplied email/password is correct. There is no guarantee that the create
action is actually calling sign_in
or current_user
.
Even if I re-write the test to check that these methods are called, it's possible that other methods could be called e.g. sign_out
.
Is there a more definitive way to ultimately check if a user is logged in, and if so, who the user is?
EDIT -
For example, the following test will pass
it 'must sign in a user' do
@controller.current_user.must_equal nil
post :create, format: :js, user: {email: @user.email, password: @user.password, remember_me: 0}
assert_response :success
@controller.current_user.must_equal @user
end
when the SessionsController#create action is:
def create
respond_to do |format|
format.js {
render nothing: true, status: 200
}
end
end
.current_user
a method that attempts to log the user in, or is it an attr_reader for an instance variable? If the former, then it seems what you're describing is the expected behavior. – Aircraftmancurrent_user
is a method that will attempt to log the user in. If you run the test I outlined in the question with a completely empty controller action, the test will still pass – Diogenessession
? – Curator