Hello, I am trying to update tests that come with phoenix autogenerated auth layer, specifically on this function
def on_mount(:ensure_authenticated, _params, session, socket) do
socket = mount_current_user(socket, session)
if socket.assigns.current_user do
{:cont, socket}
else
socket =
socket
|> Phoenix.LiveView.put_flash(:error, "You must log in to access this page.")
|> Phoenix.LiveView.redirect(to: ~p"/login")
{:halt, socket}
end
end
and its tests:
describe "on_mount: ensure_authenticated" do
test "redirects to login page if there isn't a valid user_token", %{conn: conn} do
user_token = "invalid_token"
session = conn |> put_session(:user_token, user_token) |> get_session()
socket = %LiveView.Socket{
endpoint: EasyBillsWeb.Endpoint,
assigns: %{__changed__: %{}, flash: %{}}
}
{:halt, updated_socket} = UserAuth.on_mount(:ensure_authenticated, %{}, session, socket)
assert updated_socket.assigns.current_user == nil
assert updated_socket.assigns.flash["error"] == "You must log in to access this page."
assert redirected_to(updated_socket) == ~p"/login"
end
test "redirects to login page if there isn't a user_token", %{conn: conn} do
session = conn |> get_session()
socket = %LiveView.Socket{
endpoint: EasyBillsWeb.Endpoint,
assigns: %{__changed__: %{}, flash: %{}}
}
{:halt, updated_socket} = UserAuth.on_mount(:ensure_authenticated, %{}, session, socket)
#failing
assert updated_socket.assigns.current_user == nil
assert updated_socket.assigns.flash["error"] == "You must log in to access this page."
#failing
assert redirected_to(updated_socket) == ~p"/login"
end
end
I want to test the redirection happens back to login page. Above, I have added two tests lines in each test block, the flash error assertion and the next line to assert the redirection happens which is failing.
I realise I can’t use redirected_to/2
with socket
as I would with conn
, which limits me only to test the presence of specific data in the socket.assigns
or flash messages.
But I would wish to assert that the redirection happened.
Any help achieving this will be appreciated.
Thanks.