ravernkoh
Wallaby testing when browser session is required (i.e. login)
How do I test some code if a browser session with some user data inside (perhaps from Guardian) is required? How do I get that session data into my Wallaby session?
Most Liked
thomasbrus
For future reference in case anyone bumps into this:
# test/support/test_helpers.ex
defmodule MyAppWeb.TestHelpers do
@user_remember_me "_my_app_web_user_remember_me"
def log_in(%{session: session} = context) do
user = Map.get(context, :user, user_fixture())
user_token = MyApp.Accounts.generate_user_session_token(user)
endpoint_opts = Application.get_env(:dorado, MyAppWeb.Endpoint)
secret_key_base = Keyword.fetch!(endpoint_opts, :secret_key_base)
conn =
%Plug.Conn{secret_key_base: secret_key_base}
|> Plug.Conn.put_resp_cookie(@user_remember_me, user_token, sign: true)
session
|> visit("/")
|> set_cookie(@user_remember_me, conn.resp_cookies[@user_remember_me][:value])
{:ok, %{session: session, user: user}}
end
end
This assumes you created MyApp.Accounts via mix phx.gen.auth. The test setup can then simply look like this:
setup context do
log_in(context)
end
hubertlepicki
I see this discussion reanimated and maybe just 2 cents from me. I usually solve this with having “autologin” controller, and corresponding route that are only present if Mix.env() == :test.
Then, I just do “visit /autologin/:user_id” as a first step of the test and user is logged in to the account specified by ID.
Again, this needs to be deployed carefully so that the route nor controller are not present in other environments, but should work well with Playwright and Wallaby alike.
NobbZ
Yes. That’s what setup is for. Or you can write a helper function that does this.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #javascript
- #code-sync
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








