Testing liveviews requiring users to be logged in.

I'm only using the magic link strategy and I'm following the test setup from tunez to configure my tests. However, I'm getting this error - ** (KeyError) key :token not found in: %{selected: [:id, :role, :email, :updated_at, :inserted_at, :organization_id]} when I try to create a user and sign it in for the test. this is the test:
test "error for forbidden users", %{conn: conn} do
conn
|> insert_and_authenticate_user(:user)
|> visit(~p"/restricted-area")
|> assert_path("/")
end
test "error for forbidden users", %{conn: conn} do
conn
|> insert_and_authenticate_user(:user)
|> visit(~p"/restricted-area")
|> assert_path("/")
end
the insert_and_authenticate_user function is the same as the one from tunez. Also, I checked that the user is being created and being passed to AshAuthentication.Plug.Helpers.store_in_session(user). I'm not sure how to solve/fix the missing :token thing
Solution:
Solved the issue. registration is disabled, so I had do create a user with a regular create action. then to sign in I had to perform the following incantation: ``` strategy = AshAuthentication.Info.strategy!(MyApp.Accounts.User, :magic_link) {:ok, token} = AshAuthentication.Strategy.MagicLink.request_token_for(strategy, user)...
Jump to solution
1 Reply
Solution
ggarciajr
ggarciajr4mo ago
Solved the issue. registration is disabled, so I had do create a user with a regular create action. then to sign in I had to perform the following incantation:
strategy = AshAuthentication.Info.strategy!(MyApp.Accounts.User, :magic_link)
{:ok, token} = AshAuthentication.Strategy.MagicLink.request_token_for(strategy, user)

{:ok, signed_in_user} =
AshAuthentication.Strategy.action(strategy, :sign_in, %{"token" => token})

conn
|> Phoenix.ConnTest.init_test_session(%{})
|> AshAuthentication.Plug.Helpers.store_in_session(signed_in_user)
strategy = AshAuthentication.Info.strategy!(MyApp.Accounts.User, :magic_link)
{:ok, token} = AshAuthentication.Strategy.MagicLink.request_token_for(strategy, user)

{:ok, signed_in_user} =
AshAuthentication.Strategy.action(strategy, :sign_in, %{"token" => token})

conn
|> Phoenix.ConnTest.init_test_session(%{})
|> AshAuthentication.Plug.Helpers.store_in_session(signed_in_user)

Did you find this page helpful?