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: "user2@test.com"})
      conn = assign(conn, :current_user, user2)
      IEx.pry
      before_count = Enum.count(Auction.list_items())
      post conn, "/items", %{"item" => %{"title" => "Item 1"}}
      assert Enum.count(Auction.list_items()) == before_count + 1
    end
  end

And here is the function I am testing:

def create(conn, %{"item" => item_params}) do
    IEx.pry
    user_id = conn.assigns.current_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)
    end
  end

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 = conn.assigns.current_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