I’m having trouble testing a LiveView with my Guardian plug.
I have a store that shows a list of products but only to authenticated users. The products are on a LiveView page.
I’ve set up a simple LiveView test (I’ve never written LiveView tests before so I’m not 100% sure this is how you would set it up).
defmodule StoreWeb.PartLiveTest do
@moduledoc false
use StoreWeb.ConnCase
import PacksizeNow.Factory
import Phoenix.LiveViewTest
alias StoreWeb.PartLive.Index
test "Returns the live-path to edit an item", %{conn: conn} do
html = live(conn, "/live/store")
#assertions to follow below
end
end
This results in an error:
{:error,
{:redirect,
%{
flash: "SVMNNTY.g2gDdGGGAAACBuBgCPpiwbdwFiAAFRgA.mpLMgb29Cm12wj8XthKTuSFnIu6pD5lffBSfZWJM",
to: "/sign-in"
}}}
Which I would expect because this page is piped through a Guardian plug.
In controller tests, we use a method called to_authenticated
to authenticate users.
def to_authenticated(%Conn{} = conn, %{} = user), do: GuardianPlug.sign_in(conn, user)
But adding this to my test does not authenticate the user, I still get the same error message. It seems like the LiveView is traversing a different path than the controllers and that sign_in/2
does not work the same way in these tests.
What is the best way to authenticate a session for LiveView tests? Has anyone else used Guardian for authentication and tested LiveViews?