Skip to content

Instantly share code, notes, and snippets.

@tsubery
Last active May 17, 2022 21:50
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tsubery/2e7d118a51702c1e24741b9e2d9dfdbf to your computer and use it in GitHub Desktop.
Save tsubery/2e7d118a51702c1e24741b9e2d9dfdbf to your computer and use it in GitHub Desktop.
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 initialized 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
@tsubery
Copy link
Author

tsubery commented Feb 5, 2020

Thank you too!

@Kintull
Copy link

Kintull commented Mar 17, 2020

Thank you very much!

@barttenbrinke
Copy link

Awesome 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment