Problem using assign in Phoenix test

I am writing a test in Phoenix app to test a create function in a controller. Here is copy of the test code:

describe "POST /items" do
    test "with valid params, creates a new Item", %{conn: conn} do
      {:ok, user2} = Auction.Repo.insert(%Auction.User{email_address: ""})
      conn = assign(conn, :current_user, user2)
      before_count = Enum.count(Auction.list_items())
      post conn, "/items", %{"item" => %{"title" => "Item 1"}}
      assert Enum.count(Auction.list_items()) == before_count + 1

And here is the function I am testing:

def create(conn, %{"item" => item_params}) do
    user_id =
    item_params = Map.put(item_params, "user_id", user_id)
    case Auction.insert_item(item_params) do
      {:ok, item} -> redirect(conn, to: Routes.item_path(conn, :show, item))
      {:error, item} -> render(conn, "new.html", item: item)

The problem i am having is I make a call to
conn = assign(conn, :current_user, user2) in test, which I can confirm populates current_user. But when the IP reaches the create function a call is made to user_id =,
which fails because current_user is nil.

Can anyone explain what is happening here?

Can you please enclose your code blocks in triple backticks (```)? Your post is unreadable.

I have added markdown format to your post.

It’s difficult to read if You don’t format code :slight_smile:

This was simply an oversight on my part. My authentication plug reset current_user to nil without finding the proper session information. Once I corrected this, the test passed.

Many thanks to those who helped me format my post.

1 Like