Authenticated Live View Tests

I’ve been running through Pragmatic Studio’s Live View course, which I highly recommend, and wanted to make a specific note of how to authenticate users when writing Live View tests after adding phx_gen_auth to a Phoenix project.

Happily, this is a very short post, because phx_gen_auth does all the work for you. When you’ve run that generator, you get a function added to your conn_case.ex called register_and_log_in_user. This function takes a map with a connection in it, creates a new user, logs the user in, and returns it with a modified connection.

So now my test that used to fail because the page now requires authentication:

    test "saves new message", %{conn: conn} do
      {:ok, index_live, _html} = live(conn, Routes.message_index_path(conn, :index))

      assert index_live |> element("a", "New Message") |> render_click() =~
               "New Message

---

     ** (MatchError) no match of right hand side value: {:error, {:redirect, %{flash: "SFMyNTY.g2gDdAAAAAFtAAAABWVycm9ybQAAACRZb3UgbXVzdCBsb2cgaW4gdG8gYWNjZXNzIHRoaXMgcGFnZS5uBgCMD68zeQFiAAFRgA.zriUcbZsaCi0a4Bqq-hpJK0WP8IH-MHusGt3DPw028g", to: "/users/log_in"}}}

Will pass if I just call that function at the front:

    test "saves new message", %{conn: conn} do
      # 🚨 Add this line to authenticate the test request.
      %{conn: conn} = register_and_log_in_user(%{conn: conn})
      {:ok, index_live, _html} = live(conn, Routes.message_index_path(conn, :index))

      assert index_live |> element("a", "New Message") |> render_click() =~
               "New Message


Posted

in

by

Tags:

Comments

2 responses to “Authenticated Live View Tests”

  1. Richard T. Avatar
    Richard T.

    Thanks for this. I spun up a new Phoenix app, moved some routes behind auth and ran into the same problem and this is the only fix that’s worked.

    1. Murphy Avatar
      Murphy

      I’m glad you found it useful!

Leave a Reply

Your email address will not be published. Required fields are marked *