⚙️ Set your preferred CLI env for mix aliases

Notes

At some point, you might introduce a new mix alias to run a subset of your tests.

It might be that you only want to run feature tests or live tests or that you want a special command to include tests that hit external resources (maybe something you only run once a day in CI).

Say, we have an alias to run our feature tests (which we tagged with live):

mix test.live

But when we try to run that command, we get an error!

** (Mix) "mix test" is running in the "dev" environment.

We could, of course, fix that by specifying MIX_ENV=test when we run the mix command.

MIX_ENV=test mix test.live

But that’s so frustrating! 😩

Thankfully, there’s a better way!

We can simply specify the preferred CLI environment for our script with preferred_cli_envs in your project definition. 🙌

defp preferred_cli_envs do
  ["test.live": "test"]
end

Update since Elixir 1.15

It seems that since Elixir 1.15 you don’t have to add a preferred_cli_envs key in the project. You can simply specify it in a new cli/0 function like this:

  def cli do
    [
      preferred_envs: ["test.live": :test]
    ]
  end

For more, see Mix.Project’s CLI configuration

Want the latest Elixir Streams in your inbox?

    No spam. Unsubscribe any time.