Run a custom migration in a test

I’m trying to figure out how to run a custom migration in a test, while using the ecto sandbox.

I have a test file where I do Ecto.Migrator.up in the setup and Ecto.Migrator.down in the on_exit.

This is how far I’ve gotten already:
When I ignore the sandbox and don’t checkout the sandbox in my test and run the test in isolation, it works fine.
When I run the test in the test suite though, I get errors that some PID is still using the connection and OwnershipErrors.

I’ve played with checkout and mode shared but nothing seems to fix the issue.

Does anyone know a possible fix?
My only solution so far is to run this test file completely separate from the rest of the suite.

  1. Define another Repo
defmodule TestRepo do
  use Ecto.Repo, otp_app: :bodleian, adapter: Ecto.Adapters.Postgres
end
  1. Run your migration and revert it with that Repo
@repo_options Application.get_env(:my_app, MyApp.Repo)
setup do
  TestRepo.start_link(@repo_options)
  Ecto.Migrator.run(TestRepo, [{0, TestMigration}], :up, all: true)
  TestRepo.stop()

  on_exit(fn ->
    TestRepo.start_link(@repo_options)
    Ecto.Migrator.run(TestRepo, [{0, TestModel.Migration}], :down, all: true)
    TestRepo.stop()

    :ok
  end)
end
1 Like