rld
rld

Reputation: 2763

Code.LoadError on import_config "#{Mix.env}.exs"

I put import this on the config.exs file:

use Mix.Config
import_config "#{Mix.env}.exs"

or

import_config "#{Mix.env()}.exs"

And when I try to run mix test it's complaining this:

mix test                                    
** (Code.LoadError) could not load /Users/romenigld/workspace/elixir/ebooks/issues/config/test.exs
    (elixir) lib/code.ex:1147: Code.find_file/2
    (elixir) lib/code.ex:706: Code.eval_file/2
    (mix) lib/mix/config.ex:187: anonymous fn/2 in Mix.Config.__import__!/2
    (elixir) lib/enum.ex:1925: Enum."-reduce/3-lists^foldl/2-0-"/3
    (mix) lib/mix/config.ex:186: Mix.Config.__import__!/2
    (stdlib) erl_eval.erl:680: :erl_eval.do_apply/6
    (elixir) lib/code.ex:232: Code.eval_string/3

It's a bug or I need to do something different?

Upvotes: 1

Views: 1662

Answers (1)

J. Random Coder
J. Random Coder

Reputation: 1342

How import_config/1 works

From Mix.Config#import_config/1:

Imports configuration from the given file or files.

[...]

If path_or_wildcard is not a wildcard but a path to a single file, then that file is imported; in case the file doesn't exist, an error is raised.

If path/wildcard is a relative path/wildcard, it will be expanded relatively to the directory the current configuration file is in.

How Mix.env/0 works

From Mix#env/0:

Returns the Mix environment.

When your application starts it will read the value from the environment varialbe MIX_ENV or set :dev if the environment variable is not set. Combare implementation.

The task that runs when you call mix test tells Mix to default to the :test environment through the @preferred_cli_env attribute.

Combining import_config/1 and Mix.env/1

Having a line of code equivalent to

import_config "#{Mix.env()}.exs"

will be evaluated at compile time (when running mix test for the first time) to

import_config "test.exs"

As the path is relative it will look for the file test.exs in the same directory where the file that contains the call to import_config is located.

In your case that is /Users/romenigld/workspace/elixir/ebooks/issues/config/ so you have to create a valid config file in /Users/romenigld/workspace/elixir/ebooks/issues/config/test.exs and also for all other environments your application should run in (probably dev and prod).

You can get around creating config files for all environments by checking the environment before you call import_config:

unless Mix.env() == :prod do
  import_config("#{Mix.env()}.exs")
end

Upvotes: 3

Related Questions