I have been working with a LiveView that needs to know who the current user is when they are performing certain operations.
Normally I would have the current user stored in the conn
but in this case we can’t fake that out because the conn
is transferring the current user to the session
which then needs to assign it in the socket
.
In this case I am using Guardian for authentication.
This results in code that looks something like this in the LiveView:
where AuthHelper
is something like:
And this works really well.
But when I was calling tests on a component associated with this LiveView I was running into trouble. I would get errors like:
** (ArgumentError) cannot put/delete request cookies after cookies were fetched
or if I tried to recycle the conn myself something like:
** (FunctionClauseError) no function clause matching in Phoenix.LiveViewTest.connect_from_static_token/2
The trick is how to setup authentication in the tests. I needed to be able to set data in the session, but in a way that the session could still be fetched in the future. The function that does this is: Plug.Test.init_test_session/2
And with that Phoenix and LiveView are able to properly get the current user into the session
and subsiquently into the socket
.
Be safe. And take care of each other.
– MM