Skip to content

Difficulty setting the session in tests #861

@crismali

Description

@crismali

I was trying to test an action that would clear the session, but I ran into a bit of trouble.

First I tried setting the session:

use MyApp.ConnCase

setup do
  conn = conn()
  {:ok, conn: conn}
end

test "DELETE /sign_out clears the session", %{conn: conn} do
  conn = conn
    |> put_session(:foo, "bar") # raises ** (ArgumentError) session not fetched, call fetch_session/2
    |> delete(session_path(conn, :delete))

  refute get_session(conn, :foo)
end

Next I followed the error to fetch_session:

test "DELETE /sign_out clears the session", %{conn: conn} do
  conn = conn
    |> fetch_session # raises ** (ArgumentError) cannot fetch session without a configured session plug
    |> put_session(:foo, "bar")
    |> delete(session_path(conn, :delete))

  refute get_session(conn, :foo)
end

I followed that error to configure_session:

test "DELETE /sign_out clears the session", %{conn: conn} do
  conn = conn
    |> configure_session(true) # raises ** (ArgumentError) session not fetched, call fetch_session/2
    |> fetch_session
    |> put_session(:foo, "bar")
    |> delete(session_path(conn, :delete))

  refute get_session(conn, :foo)
end

And I tried passing different arguments to configure_session:

test "DELETE /sign_out clears the session", %{conn: conn} do
  conn = conn
    |> configure_session(renew: true) # raises ** (ArgumentError) session not fetched, call fetch_session/2
    |> fetch_session
    |> put_session(:foo, "bar")
    |> delete(session_path(conn, :delete))

  refute get_session(conn, :foo)
end

test "DELETE /sign_out clears the session", %{conn: conn} do
  conn = conn
    |> configure_session(drop: true) # raises ** (ArgumentError) session not fetched, call fetch_session/2
    |> fetch_session
    |> put_session(:foo, "bar")
    |> delete(session_path(conn, :delete))

  refute get_session(conn, :foo)
end

Not sure, but it looks like there might be a chicken and the egg sort of problem here.

I'm not sure if this is more of a Phoenix issue or a Plug issue, but it seems to me that conn should come out ready to have arbitrary data added to the session.

There might also be no issue and I'm just missing something of course =)

Also, this is how I worked around it:

test "DELETE /sign_out clears the session", %{conn: conn} do
  create_user(@user_attrs)
  conn = conn
    |> post(session_path(conn, :create), @valid_params)
    |> delete(session_path(conn, :delete))

  refute get_session(conn, :foo)
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions