Why Phoenix Recycling?

I’m writing tests for my controller:

  defp log_in_user(%{conn: conn, log_in_as: email}) do
    role = role_fixture()
    user = user_fixture(role, email: email)
    conn = assign(conn, :current_user, user)
    {:ok, conn: conn, user: user}
  end

  defp create_site(%{conn: conn, user: user}) do
    site = site_fixture(user)
    {:ok, site: site}
  end

  describe "delete site" do
    setup [:log_in_user, :create_site]

    @tag log_in_as: "sam"
    test "deletes chosen site", %{conn: conn, site: site} do
      conn = delete(conn, Routes.site_path(conn, :delete, site))
      assert redirected_to(conn) == Routes.site_path(conn, :index)

      assert_error_sent 404, fn ->
        get(conn, Routes.site_path(conn, :show, site))
      end
    end
  end

The weird thing here is conn.assigns.current_user becomes nil in assert_error_sent where it should have value.

I found some similar questions around the web:

  1. Troubleshooting a failed test 302 redirect instead of 200 - #3 by chensan
  2. https://stackoverflow.com/questions/50110449/phoenix-controller-test-case-loses-current-user
  3. https://stackoverflow.com/questions/46363292/losing-conn-assigns-in-the-middle-of-a-test

Seems the problem is caused by Phoenix.ConnTest – Phoenix v1.4.0, and there’s a fix:

      saved_assigns = conn.assigns

      conn =
        conn
        |> recycle()
        |> Map.put(:assigns, saved_assigns)

I don’t quite understand why, it’s so unexpected in our tests. Anyone could help explain it?