Is it possible to `log_in_user(conn, user)` inside setup tag of LiveView tests?

I sometimes have to log a user in at the top of all the tests of a describe block. Like so:

describe "some set of tests" do
  test "A", %{conn: conn} do
    conn = log_in_user(conn, user)

    # do something
    # assert or refute something
  end

  test "B", %{conn: conn} do
    conn = log_in_user(conn, user)

    # do something
    # assert or refute something
  end

  test "C", %{conn: conn} do
    conn = log_in_user(conn, user)

    # do something
    # assert or refute something
  end
end

Is there anyway to log in a user in a setup tag, instead? Something like:

describe "some set of tests" do
  setup do
    %{conn: log_in_user(new_conn(), user_fixture())}
  end

  test "A", %{conn: conn} do
    # do something
    # assert or refute something
  end

  test "B", %{conn: conn} do
    # do something
    # assert or refute something
  end

  test "C", %{conn: conn} do
    # do something
    # assert or refute something
  end
end

I looked for solutions online, and mainly in the official documentation, but I can’t seem to find the info I am looking for.

There most certainly is:

  describe "home page" do
    setup %{conn: conn} do
      user = user_fixture()

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

    test "load homepage if logged in", %{conn: conn, user: user} do
      {:ok, _lv, html} =
        conn
        |> live(~p"/home")

      assert html =~ user.username
    end
  end

Just ran this in a local project of mine, works swimmingly

3 Likes

Oh yes. That makes sense.

It never occurred to me to try:

setup x do
  x |> dbg()
end

To see what is passed by default to setup.

Thank you.

1 Like

If you happen to be using phx_gen_auth (and it looks like you might) it generates a register_and_log_in_user/1 helper in your MyAppWeb.ConnCase. So you can do:

setup :register_and_log_in_user

2 Likes