elixir-plug / plug

Compose web applications with functions
https://hex.pm/packages/plug
Other
2.84k stars 582 forks source link

How to fix "Plug.Conn.AlreadySentError" when running tests in Phoenix? #1139

Closed belwalshubham closed 1 year ago

belwalshubham commented 1 year ago

I'm getting a "Plug.Conn.AlreadySentError" when running tests in my Phoenix application. Specifically, the error message says:

test lists all user (DbserviceWeb.UserControllerTest)
test/dbservice_web/controllers/user_controller_test.exs:69
** (Plug.Conn.AlreadySentError) the response was already sent
code: conn = get(conn, Routes.user_path(conn, :index))

How can I fix this error? Here's my test code:

 setup %{conn: conn} do
    {:ok, conn: put_req_header(conn, "accept", "application/json")}
  end

  describe "index" do
    test "lists all user", %{conn: conn} do
      conn = get(conn, Routes.user_path(conn, :index))
      [head | _tail] = json_response(conn, 200)
      assert Map.keys(head) == @valid_fields
    end
  end

I guess this happening because there is already a get method being used inside the Conn module, and calling get again on the same connection causes the "AlreadySentError. I understand that this error occurs when the response has already been sent before the test can complete. However, I'm not sure how to fix it. Can someone please help me understand what's causing this error and how to fix it?

josevalim commented 1 year ago

Please use the ElixirForum for questions/help/feedback, where a wider community will be able to help you. Thank you!