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.
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?
Thanks @Exadra37, there are definitely good LiveView resources out there but nothing on how to Authenticate the conn with Guardian before running the tests.
Then you have the pragmaticstudio.com phoenix paid course which also explains testing a live-view with phx.gen.auth in lesson 29 but it’s very short / not that much material, mostly because it’s also pretty short to do. (But it has a pretty thorough walkthrough of using phx.gen.auth of about 30 mins before it (lesson 28) if you would like to switch over )
Lastly, I did a github.com wide code search given this query: guardian "Phoenix.LiveViewTest" language:elixir and only one repo/commit came up namely the following: https://github.com/NicFisher/elixir-todo/blob/master/test/todo_web/live_views/live_view_board_test.exs
This is actually a test mixing authenticating live view and guardian, so all these combined should put you well on your way forward hopefully! If not, you could always post some minimal repo example and people are better able to help through code.