Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to set session in phoenix controller tests

If you are reading this, you probably tried to write code like this

test "testing session" do
  build_conn()
  |> put_session(:user_id, 234)
  |> get("/")
  ...
  end

And got this exception:

(ArgumentError) session not fetched, call fetch_session/2

The reason for this error is that Plug expects session to be initialize before allowing any access. One way to solve it is to add the following to support/conn_case.ex

  using do
    quote do
    
      ... #don't add this line :)
      
      def session_conn() do
        build_conn() |> Plug.Test.init_test_session(%{})
      end
    end
  end

Now your tests can use session_conn() to build a Plug.Conn with initialized session. For example:

test "testing session" do
  session_conn()
  |> put_session(:user_id, 234)
  |> get("/")
  ...
  end
@AdamT

This comment has been minimized.

Copy link

@AdamT AdamT commented Jan 12, 2020

Thanks for this 👏

@rjurado01

This comment has been minimized.

Copy link

@rjurado01 rjurado01 commented Jan 22, 2020

You can use this: Plug.Test.init_test_session(conn, current_user_id: 1)

Source: https://paulhoffer.com/2018/03/22/easy-session-testing-in-phoenix-and-plug.html

@tsubery

This comment has been minimized.

Copy link
Owner Author

@tsubery tsubery commented Jan 26, 2020

Thanks!

@kenny-evitt

This comment has been minimized.

Copy link

@kenny-evitt kenny-evitt commented Feb 5, 2020

It seems like init_test_session requires a second argument/parameter, at least in the version of Plug I'm using – 1.8.3. The minimal call seems to be build_conn() |> Plug.Test.init_test_session(%{}).

@tsubery

This comment has been minimized.

Copy link
Owner Author

@tsubery tsubery commented Feb 5, 2020

Thank you too!

@Kintull

This comment has been minimized.

Copy link

@Kintull Kintull commented Mar 17, 2020

Thank you very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.