How to test live views with ash authentication plugs

after a lot of trial and error, and inspecting the connection after login, I saw that a “user” was stored in the session in the form of

      "user" => "user?id=ef6f74a3-3795-4f0d-be4f-622db62f8c01"

so I made it all work in the tests by doing this:

  setup %{conn: conn} do
    user =
      AshActivityPlanner.Accounts.User
      |> Ash.Changeset.for_create(:register_with_password, %{
        email: "test@user.com",
        password: "password",
        password_confirmation: "password"
      })
      |> AshActivityPlanner.Accounts.create!()

    {:ok, %{conn: log_in_user_as_subject(conn, user)}}
  end

  # SNIP ...

  defp log_in_user_as_subject(conn, user) do
    subject = AshAuthentication.user_to_subject(user)

    conn
    |> Phoenix.ConnTest.init_test_session(%{})
    |> Plug.Conn.put_session("user", subject)
  end
5 Likes