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?