I’m curious if anybody has used the built in rails authentication generator and figured out a way to login/sign_out a user automatically like you could do with devise.
Currently I was adding a line to sign in to the user account in the system test but this causes issues when I run multiple tests with other role types and it just says the user is already logged in.
I need to find a way to login the user on setup and possibly log out on the teardown callback for minitest.
I ended up solving this by writing a helper method which conditionally logs out if the user dropdown is there. And this works for me in the system tests so just wanted to update this with my solution
def login_as(user)
# Logout existing user
begin
if find('#user-menu-button')
find("#user-menu-button").click
click_on "Sign out"
end
rescue Capybara::ElementNotFound
end
# Login new user
temp_password = SecureRandom.uuid
user.update(password: temp_password)
visit new_session_path
fill_in "Enter your email address", with: user.email_address
fill_in "Enter your password", with: temp_password
click_on "Sign in"
end
It would be nice if there was a helper to set cookies/session keys in system test. I think thats how devise worked but I’m not sure
Here are the helpers I created for my app based on the ones for requests specs
def sign_in(user = users(:matz))
session = user.sessions.create!
Current.session = session
request = ActionDispatch::Request.new(Rails.application.env_config)
cookies = request.cookie_jar
cookies.signed[:session_id] = { value: session.id, httponly: true, same_site: :lax }
end
alias_method :sign_in_as, :sign_in
def log_out
Current.session.destroy
request = ActionDispatch::Request.new(Rails.application.env_config)
cookies = request.cookie_jar
cookies.delete(:session_id)
end
2 Likes
Thanks this looks really awesome, was just what I was looking for.
1 Like
Hey I’m still seeing an issue where when I run the tests individually they pass but when I run all system tests using./bin/rails test:system
it doesn’t work. It seems like the account is still logged in with the wrong role.
I’m currently running the logout method and then the login method.
Update: I fixed this
I was putting my login/logout code in setup/teardown callbacks but I guess when rails runs the system tests in parallel it doesn’t really use these methods correctly. I fixed my tests by moving the logout/login code into each test I run and it works now! So thanks for your solution I just had to modify my code to log/login inside of each test so they can run in parallel
1 Like