Skip to content

Controller testing new authentication generator. #53207

@gobijan

Description

@gobijan

In Rails 8 Beta 1 we got the new authentication generator.
This now opens the question how we test controllers that need a signed in user.

Performance wise it might be nice to have a programatic login_as(user) method that does NOT rely on creating a POST request in front of every request to log a user in as seen in this solution:

def sign_in(user, password: "password")
  post session_url, params: { email_address: user.email_address, password: }
end

In the new authentication scope we have:

def find_session_by_cookie
  Session.find_by(id: cookies.signed[:session_id])
end

But Rack::Test::CookieJar doesn't define signed.

eval error: undefined method `signed' for an instance of Rack::Test::CookieJar

I monkey patched in my test helpers like it's 2009:

ENV["RAILS_ENV"] ||= "test"
require_relative "../config/environment"
require "rails/test_help"

module ActiveSupport
  class TestCase
    # Run tests in parallel with specified workers
    parallelize(workers: :number_of_processors)

    # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
    fixtures :all

    # Add more helper methods to be used by all tests here...
    def login_as(user)
      session = user.sessions.create!(user_agent: "test", ip_address: "127.0.0.1")
      Current.session = session
      cookies[:session_id] = session.id
    end

  end
end

# Monkey-patch the Authentication concern for test environment
module Authentication
 private
   def find_session_by_cookie
     Session.find_by(id: cookies[:session_id])
   end
end

Maybe we do something here? Any suggestions? Implement a signed on the Rack::Test::CookieJar?
Should the generator come up with a test helper?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions