Test for sessions in Phoenix

Is there any way to put_session in a test, I want to test my logout and I haven’t found a way to setup the conn with a sessionput_session(conn, myid), something like the code, but seems difficult to setup a session in Plug

setup do
   conn = build_conn
   |> put_session(:myid, "myvalue")

   %{conn, conn}
end
3 Likes

I’m no an elixir expert but this worked for me:

  setup %{conn: conn} do
    setup_conn = 
      conn
      |> bypass_through(MyApp.Router, :browser)
      |> get("/")
      |> put_session(:my_id, "myvalue")
      |> send_resp(:ok, "")
    {:ok, %{conn: setup_conn}}
  end

To put something into a conn session in a Phoenix test you first have to go through you app’s router and then back.


from http://mikker.github.io/2016/05/14/sign-in-as-a-user-in-phoenix-controller-tests.html :

4 Likes

Plug.Test.init_test_session(conn, :my_id, "myvalue") could be used instead of bypass_through + `put_session(conn, :my_id, “myvalue”):

  setup %{conn: conn} do
    setup_conn = 
      conn
      |> Plug.Test.init_test_session(:my_id, "myvalue")      
      |> get("/")
      |> send_resp(:ok, "")
    {:ok, %{conn: setup_conn}}
  end
1 Like

For anyone hitting this now, erujolc’s answer should be considered the way to do this.

2 Likes