Using session cookies directly in playwright

After 37signals posted how they sped up their test suite considerably by using cookies directly instead of signing a user in for every test, I wanted to do the same. Why spend more time than necessary on testing, am I right?

Unfortunately, it wasn't as easy as I thought it would be. I had to ask for help to sort this one out.

To avoid crashing all tests at once, I created an additional method, and my system helper now looks like this:

lang-rb
# frozen_string_literal: true

require "capybara/rspec"

module LoginHelper
  def sign_in_as(user)
    visit sign_in_path(locale: user.locale)

    find_by_id("btn-accept-cookies").click if ENV["COOKIE_BANNER"]

    raise "No user password" unless user.password

    fill_in :email, with: user.email
    fill_in :password, with: user.password
    click_on I18n.t("cmd.sign_in", locale: user.locale)
  end

  def fake_sign_in_as(user)
    session    = user.sessions.create!
    cookie_jar = ActionDispatch::TestRequest.create.cookie_jar
    cookie_jar.signed.permanent[:session_token] = { value: session.id }

    page.driver.with_playwright_page do |page|
      page.context.add_cookies([
        { url: Capybara.app_host, name: "session_token", value: cookie_jar[:session_token] }
      ])
    end

    user
  end
end

RSpec.configure do |config|
  config.include LoginHelper, type: :system
end