Using Ecto dependency only for tests

I need to test functions operating on data coming from Ecto.Repo functions; so I need to use a database and ecto and ecto_sql. I need these dependencies only for my tests.

I added in mix.exs:

{:ecto, "~> 3.4", only: :test},
{:ecto_sql, "~> 3.4", only: :test},

and added a test.exs config file:

config :my_lib,
  ecto_repos: [MyLib.Repo]

config :my_lib, MyLib.Repo,
  username: "postgres",
  password: "postgres",
  database: "my_lib_test",
  hostname: "localhost",
  pool: Ecto.Adapters.SQL.Sandbox,
  priv: "test/support"

Running mix test gives the following error:

[error] Postgrex.Protocol (#PID<0.1783.0>) failed to connect: ** (Postgrex.Error) FATAL 3D000 (invalid_catalog_name) database “my_lib_test” does not exist

Then I try to run mix ecto.create, but it says:

** (Mix) The task “ecto.create” could not be found

Then I try to remove only: test in mix.exs, just out of curiosity, so update it to:

{:ecto, "~> 3.4"},
{:ecto_sql, "~> 3.4"},

Then run mix ecto.create again, and I have the following error:

warning: could not find Ecto repos in any of the apps: [:my_lib].

(well, probably because the repo is configured only in the test.exs file)

Why can’t the mix task be found when these dependencies are configured for test only?

Thank you for any help :hot_face:

Mix will default to the :dev environment, except for the test task that will default to the :test environment. The environment can be changed via the MIX_ENV environment variable:

Unix-like:

MIX_ENV=test mix ecto.create 

Windows:

> set "MIX_ENV=test" && mix ecto.create 

From the docs:

4 Likes

In Windows it says

‘MIX_ENV’ is not recognized as an internal or external command,
operable program or batch file.

And are you sure this is the correct way? Because I wonder:

  1. Why can’t mix detect that I have added the only: test option for ecto and ecto_sql?
  2. Why isn’t there an option such as mix ecto.create --test-env?

These two lines for Windows work:

set MIX_ENV=test
mix ecto.create