Strategies to populate database before running tests

I am building a Phoenix application and am putting together a suite of tests. The tests are hitting an actual postgres database using an Ecto sandbox adapter as recommended in the docs.

I would like to ensure that there is some test data available before the tests are run (some test users, some test tenants, etc.)

What’s the recommended strategy for this in Phoenix/Ecto, here’s some ideas I have:

  1. Write a migration that inserts the test data so I can guarantee it is there. Con: Will mean the data is also in production.
  2. In the ConCase add a setup that will add the test data. Con: will slow down the tests as this will run before every test.
  3. Add the data in a setup_all but I can’t figure out how to get this working given the Sandbox.

What do you think re #3 or are there other options?

  1. Use priv/repo/seeds.exs in tests, check out a fresh mix phs.new project, in particular aliases in mix.exs and explainations in priv/repo/seeds.exs

Maybe some sort of factory setup tooling is what you’re looking for? Test factories — Ecto v3.7.1

These might be used within the setup block of a describe + test usage in exunit. e.g. ExUnit.Case — ExUnit v1.12.3

Although I’d recommend generating params and using the same functions your app would instead of maintaining separate database backfilling models.

I’d just do a combined mix task that checks if the required data is in place and inserts it if it is not. Done it before. Using Ecto.Repo.upsert helps a lot.