ravernkoh

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

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

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

NobbZ

Yes. That’s what setup is for. Or you can write a helper function that does this.

hubertlepicki

hubertlepicki

In your router:


  if Mix.env() == :test do
    scope "/autologin", Web do
      pipe_through(:browser)
      get("/:account_id", AutologinTestController, :autologin)
    end
  end

And then in your test/support/autologin_test_controller.ex:

defmodule Web.AutologinTestController do
  @moduledoc "This controller is used for tests only and is compiled
  in MIX_ENV=test environment only. It allows to log in to accounts by
  visiting /autologin/:account_id, working around Oauth2/Google login."

  use Web, :controller

  def autologin(conn, %{"account_id" => account_id}) do
    account = DB.Repo.get!(DB.Account, account_id)
    Web.LogIn.login(conn, account)
  end
end

Adjust for your code structure, but that’s roughly it. A few lines.

Remember to wrap the route in the if clause and then also put the controller in test/support rather than usual location so it doesn’t get compiled in other environments.

The Web.Login.login/2 is the same function that’s used by actual controllers so you are sure it’s setting all the session variables the same way as production code.

LostKobrakai

LostKobrakai

If you’re not concerned about phoenix’s ability to hold the session you can also test this without browser testing. You should also be able to set values to the conn’s session manually like so:

conn =
      conn
      |> bypass_through(MyAppWeb.Router, [:browser])
      |> put_session(:account_id, 1)

get conn, …

Where Next?

Popular in Questions Top

lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
Kagamiiiii
Student & New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
Phillipp
Hey, I have a NanoPi-M3 and try to install Elixir on their Ubuntu image. I followed the Raspberry Pi installation instructions from the ...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

Other popular topics Top

JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

We're in Beta

About us Mission Statement