Controller test with Task

I have a controller in which after a successful insertion, I perform the background action with Task

case Repo.insert(changeset) do
  {:ok, payment} ->
    Task.start(__MODULE__, :after_change, [payment, params])
    conn
    |> # usual redirect 
end

def after_change(payment, params) do
  order = payment |> Repo.preload(:order) |> Map.get(:order)
  # some_work_with_order(order)
end

And I have test for this controller:

test "creates resource and redirects when data is valid", %{conn: conn} do
  order = insert(:order) # use ExMachina
  conn = post conn, payment_path(conn, :create), payment: %{:order_id, order.id}
  assert Repo.get_by(Payment, order_id: order.id)
end

But the test passes with an errors
with Myapp.ConnCase: disconnected: ** (DBConnection.ConnectionError) owner #PID<0.452.0> exited while client #PID<0.460.0> is still running with: shutdown
with Backoffice.ConnCase, async: true: сan not preload in #after_change, there are no more orders in the database and order == nil

I have read Ecto.Sandbox.FAQ, but I do not know how to apply it in my case, will be glad to any advice

2 Likes