Skip to content

Commit ad5e31c

Browse files
authored
Sandbox docs: more information around start_owner! (#665)
1 parent 6ac76d9 commit ad5e31c

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

lib/ecto/adapters/sql/sandbox.ex

+13-10
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,6 @@ defmodule Ecto.Adapters.SQL.Sandbox do
4848
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Repo)
4949
end
5050
51-
setup tags do
52-
pid = Ecto.Adapters.SQL.Sandbox.start_owner!(Repo, shared: not tags[:async])
53-
on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end)
54-
:ok
55-
end
56-
5751
test "create post" do
5852
# Use the repository as usual
5953
assert %Post{} = Repo.insert!(%Post{})
@@ -417,18 +411,27 @@ defmodule Ecto.Adapters.SQL.Sandbox do
417411
end
418412

419413
@doc """
420-
Starts a process that owns the connection and returns its pid.
414+
Starts a process that will check out and own a connection, then returns that process's pid.
421415
422-
The owner process is not linked to the caller, it is your responsibility to
423-
ensure it will be stopped. In tests, this is done by terminating the pool
424-
in an `ExUnit.Callbacks.on_exit/2` callback:
416+
The process is not linked to the caller, so it is your responsibility to ensure that it will be
417+
stopped with `stop_owner/1`. In tests, this is done in an `ExUnit.Callbacks.on_exit/2` callback:
425418
426419
setup tags do
427420
pid = Ecto.Adapters.SQL.Sandbox.start_owner!(MyApp.Repo, shared: not tags[:async])
428421
on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end)
429422
:ok
430423
end
431424
425+
## `start_owner!/2` vs `checkout/2`
426+
427+
`start_owner!/2` should be used in place of `checkout/2`.
428+
429+
`start_owner!/2` solves the problem of unlinked processes started in a test outliving the test process and causing ownership errors.
430+
For example, `LiveView`'s `live(...)` test helper starts a process linked to the LiveView supervisor, not the test process.
431+
These errors can be eliminated by having the owner of the connection be a separate process from the test process.
432+
433+
Outside of that scenario, `checkout/2` involves less overhead than this function and so can be preferable.
434+
432435
## Options
433436
434437
* `:shared` - if `true`, the pool runs in the shared mode. Defaults to `false`

0 commit comments

Comments
 (0)