What to do if mix test keeps throwing this error

Compilation error in file test/MyApp/analytics_test.exs ==
** (DBConnection.OwnershipError) cannot find ownership process for #PID<0.648.0>.

When using ownership, you must manage connections in one
of the four ways:

  • By explicitly checking out a connection
  • By explicitly allowing a spawned process
  • By running the pool in shared mode
  • By using :caller option with allowed process

The first two options require every new process to explicitly
check a connection out or be allowed by calling checkout or
allow respectively.

The third option requires a {:shared, pid} mode to be set.
If using shared mode in tests, make sure your tests are not

The fourth option requires [caller: pid] to be used when
checking out a connection from the pool. The caller process
should already be allowed on a connection.

If you are reading this error, it means you have not done one
of the steps above or that the owner process has crashed.

See Ecto.Adapters.SQL.Sandbox docs for more information.
(ecto_sql 3.1.0) lib/ecto/adapters/sql.ex:602: Ecto.Adapters.SQL.raise_sql_call_error/1
(ecto 3.1.7) lib/ecto/repo/schema.ex:649: Ecto.Repo.Schema.apply/4
(ecto 3.1.7) lib/ecto/repo/schema.ex:262: anonymous fn/15 in Ecto.Repo.Schema.do_insert/4
(MyApp 1.0.0) test/support/test_helpers.ex:100: MyApp.TestHelpers.location_fixture/1
(MyApp 1.0.0) test/support/test_helpers.ex:128: MyApp.TestHelpers.fulfilment_centre_fixture/1
(MyApp 1.0.0) test/support/test_helpers.ex:255: MyApp.TestHelpers.fulfilment_centre_inventory_fixture/1
test/MyApp/analytics_test.exs:8: (module)
(stdlib 3.11.2) erl_eval.erl:680: :erl_eval.do_apply/6
(elixir 1.10.0) lib/kernel/parallel_compiler.ex:325: Kernel.ParallelCompiler.require_file/2
(elixir 1.10.0) lib/kernel/parallel_compiler.ex:235: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/7

Can you show your test_helpers.exs file? You are probably using a shared connection pool setup instead of manual? Also: do you have setup_all going on? Just guessing over here:)

For the record (for future beginners like me), I got this error when I forgot to manually checkout a connection in the setup for the test.

# In YourTest module
setup do
    # Explicitly get a connection before each test
    :ok = Ecto.Adapters.SQL.Sandbox.checkout(Repo)

For more details refer to the relevant Ecto Docs page here.


I do:

    :ok = Ecto.Adapters.SQL.Sandbox.checkout(Repo)
    Ecto.Adapters.SQL.Sandbox.mode(Repo, {:shared, self()})

But sometimes still get the error. What can we do in those cases?