Skip to content

Instantly share code, notes, and snippets.

@outofambit
Forked from tsubery/phoenix_session_test.md
Last active April 2, 2018 01:20
Show Gist options
  • Save outofambit/ed5f33a7ad18e2d7be9aee8d95eb440a to your computer and use it in GitHub Desktop.
Save outofambit/ed5f33a7ad18e2d7be9aee8d95eb440a 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 initialize before allowing any access. One way to solve it is to add the following to support/conn_case.ex inside the (likely already existing) using quote blocks

  using do
    quote do
    
      ... #don't add this line :)
      
      def session_conn() do
        opts =
          Plug.Session.init(
            store: :cookie,
            key: "foobar",
            encryption_salt: "encrypted cookie salt",
            signing_salt: "signing salt",
            log: false,
            encrypt: false
          )
        build_conn()
        |> Plug.Session.call(opts)
        |> fetch_session()
      end
    end
  end

Now your tests can use session_conn() to build a Plug.Conn with initialized session. I like to put it in a function that setup can call

For example:

describe "testing feature" do
  setup :create_session_conn
  
  test "testing session" do
    session_conn()
    |> put_session(:user_id, 234)
    |> get("/")
    ...
  end
end

defp create_session_conn(_) do
  conn = session_conn()
  {:ok, conn: conn}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment