Ash FrameworkAF
Ash Framework3y ago
3 replies
Terryble

How to test LiveView behind AshAuthentication?

I have some LiveViews that require an authenticated user to access (AshAuthentication). How do I simulate login for the user?

I saw that there are a few tests in the AshHQ repo and I did try to copy all of the relevant stuff, but I still can't get it to work. Here's what I have so far:

defmodule MyAppWeb.BookLiveTest do
  use MyAppWeb.ConnCase

  import Phoenix.LiveViewTest

  describe "with existing books" do
    setup %{conn: conn} do
      result = register_and_log_in_user(%{conn: conn})
      book = book_fixture(result[:user], %{name: "Test Book"})

      %{
        conn: result[:conn],
        user: result[:user],
        book: book
      }
    end

    test "lists all books", %{conn: conn, book: book} do
      {:ok, _index_live, html} = live(conn, ~p"/books")

      assert html =~ "Listing Books"
      assert html =~ book.name
    end
  end
end


defmodule MyAppWeb.LoginTestHelpers do
  alias MyApp.AccountsFixtures

  def register_and_log_in_user(%{conn: conn}) do
    user = AccountsFixtures.user_fixture()

    %{conn: log_in_user(conn, user), user: user}
  end

  def register_user(_context) do
    %{
      user: AccountsFixtures.user_fixture()
    }
  end

  def log_in_user(conn, user) do
    conn
    |> Phoenix.ConnTest.init_test_session(%{})
    |> Plug.Conn.put_session(:user_token, user.__metadata__.token)
  end
end
Was this page helpful?