Wallaby testing when browser session is required (i.e. login)

For future reference in case anyone bumps into this:

# test/support/test_helpers.ex
defmodule MyAppWeb.TestHelpers do
  @user_remember_me "_my_app_web_user_remember_me"

  def log_in(%{session: session} = context) do
    user = Map.get(context, :user, user_fixture())
    user_token = MyApp.Accounts.generate_user_session_token(user)

    endpoint_opts = Application.get_env(:dorado, MyAppWeb.Endpoint)
    secret_key_base = Keyword.fetch!(endpoint_opts, :secret_key_base)

    conn =
      %Plug.Conn{secret_key_base: secret_key_base}
      |> Plug.Conn.put_resp_cookie(@user_remember_me, user_token, sign: true)

    session
    |> visit("/")
    |> set_cookie(@user_remember_me, conn.resp_cookies[@user_remember_me][:value])

    {:ok, %{session: session, user: user}}
  end
end

This assumes you created MyApp.Accounts via mix phx.gen.auth. The test setup can then simply look like this:

  setup context do
    log_in(context)
  end
5 Likes