4

I wish to programmatically run the mix test task within my Elixir application. This can be done with Mix.Tasks.Test.run/1, though attempting to do so without first setting the MIX_ENV environmental variable results in the task refusing to run.

We can set the env with System.put_env/2, but then the application will crash once it finds a reference to a module defined in a dependancy marked as test only.

How can I load these dependancies in this situation?

lpil
  • 1,702
  • 1
  • 12
  • 22

1 Answers1

4

We can set the env with System.put_env/2, but then the application will crash once it finds a reference to a module defined in a dependancy marked as test only.

That's on purpose. You need to set the environment variable before Mix is started, otherwise Mix will load the wrong dependencies.

If you are creating a new task, you can tell Mix what is the preferred environment to run it by setting [preferred_cli_env: [my_task: :test]] in your project function. Other than that, you have no option besides setting MIX_ENV explicitly.

José Valim
  • 50,409
  • 12
  • 130
  • 115
  • Is it not possible to reload the deps once the env has been changed? – lpil Apr 29 '15 at 08:44
  • 1
    You definitely could. But what about code that was already loaded? Applications that have possibly been started? I would prefer my environments to be "clean" than have a mixture of dev and test code. Some frameworks do what you have mentioned but it just causes pain in the long term. – José Valim Apr 29 '15 at 09:12