New Discussion

Notifications

You’re not receiving notifications from this thread.

Rails 7.1 Authentication From Scratch - Test Helpers

2
Testing

I've implemented the Rails authentication in my 7.1 app but was wondering how to go about stubbing the current_user or session in my RSpec Request specs.

I'm normally used to have a Devise or Clearance helper that does this.

Anyone know how to do this?

For controller & integration tests, you'll make a POST request to log the user in:

class ActiveSupport::TestCase
  def login(user, password: "password")
    post login_path, params: {
      email: user.email,
      password: password
    }
  end
end

In Rails 7.1 without Devise, you can stub current_user in your request specs by defining helper methods or using Warden test helpers if you’re using Warden. Another common way is to directly set the session or use allow_any_instance_of to mock current_user in controller tests. For request specs, consider creating a helper that logs in a test user by posting to the login path or setting the session manually.

Join the discussion
Create an account Log in

Learning Ruby on Rails? Join our newsletter.

We won't send you spam. Unsubscribe at any time.