The easiest way to test a controller action that works with something (not id!) in the session

I have a pair of temporally-coupled controller actions. One, a GET that renders a form, puts a key/value pair into the session. The next action, a POST, is to combine the form values with the session value to do that thing it does. I’m trying to write the test for that second action, and I’m having trouble.

I know the trick from the Phoenix documentation of having an authorization plug that checks if a test has put a value in conn.assigns[:current_user]:

   cond do
      conn.assigns[:current_user] ->

But it seems wrong to add special-case test-support code for every session value.

So what’s the simplest way for a test to inject a value into the session with put_session (or something else) such that the controller can use a get_session to retrieve the value? If I look at the conn after the first (GET) action, I see that the information I want is nicely stored in :private:

   :plug_session => %{
      "token_text" => "Q2bPgpLDGHtf4BbHDgTfMpM6fN"
    :plug_session_fetch => :done,
    :plug_session_info => :write,

It seems that my test should be able to easily create an incoming session with the same token_text, just as if a real user had previously executed the form-producing action. But I don’t see how to do it.

Can you show what you’ve tried so far in your test case? That will make it easier for us to suggest solutions.

Have you looked at Plug.Test.init_test_session/2 yet?

@benwilson512: I must have been using init_test_session wrong. Looking back, I bet I forgot to return the changed conn from the setup method, doing something like this:

    setup %{conn: conn} do
      {:ok, user} = user_creation_params() |> Users.user_needing_activation

      conn = Plug.Test.init_test_session(conn, token_text: user.password_token.text)
      [valid_password: "something horse something something", user: user]

@peerreynders Thanks! That blog post on init_test_session was just what I needed. The code sample must have steered me away from whatever stupid mistake I’d made using it.