Ecto.create for new project does not create test database

I created a new Phoenix project: mix myproject and then modified the username and password values in the dev.exs and test.exs files but changed no other configuration values.

I then run mix ecto.create. The dev database is created but not the test database.

I then ran MIX_ENV=test mix ecto.create which created the test database.

Later I ran mix phx.gen.auth Accounts User users. And then ran mix deps.get followed by mix ecto.migrate. The users and users_tokens tables were added in the dev database but not to the test.

This has now happened on multiple new projects leading me to believe that there’s something wrong in my environment or my understanding.

That is expected behaviour.

Take a look in mix.exs under defp aliases and you’ll see this entry:

  test: ["ecto.create --quiet", "ecto.migrate --quiet", "test"],

So every time you run mix test migrations will be run for test ENV, if needed.

If you really want it to be run in both envs every time, you could make a shell alias to do so. I’ve found this gets confusing in certain situations and much prefer to have control over what env it’s running in.

For situation like rollbacks where the two can get out of sync, I add the following to my mix.exs:

  def project do
    # ...
    preferred_cli_env: [
      "test.reset": :test
    # ...

  defp aliases do
    # ...
    "test.reset": ["ecto.reset"]
    # ...

Now I can do a mix test.reset to get my test database schema back in sync.

PS, welcome to the forums!


Be careful with running ecto.reset in test. This will execute priv/repo/seeds.exs which will seed your test database with data your tests are most likely not expecting to be there.

A safer alias is:

"test.reset": ["ecto.drop", "ecto.create", "ecto.migrate"]

Oh, fair point! I did not consider this, thanks!!!

I also think it’s probably a good idea to call the task test.prepare or something else. Once I accidentally did ecto.reset instead of test.reset and I was not happy. Gonna make both these changes to my projects.

Thank you.

I guess in what I’ve done so far I had always run the tests before looking in postgres. I just deleted the database, ran the tests (all passed) and the database is now in postgres.

I appreciate the quick response.

1 Like