DEV Community

Murphy Randle
Murphy Randle

Posted on • Originally published at mrmurphy.dev on

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"}}}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)