Search code examples
elixirelixir-mixex-unit

Mix warns me about an undefined module the first time I compile in my test environment. How to ignore it?


I have a module defined in my test/ directory which is used to mock the function :crypto.strong_rand_bytes/1 which outputs random values.

In my test configuration I replace the "module" containing the function like so:

config :lottosim, :crypto, Lottosim.Test.RandomQueue


The module in the lib/ directory references this configuration by defining a module attribute:

@crypto Application.get_env(:lottosim, :crypto) || :crypto

and then the function is called with:

@crypto.strong_rand_bytes(1).


Because the module RandomQueue which is in the test/ directory is compiled after the modules in my lib/ directory, the following warning is shown the first time I compile my project with MIX_ENV=test:

warning: function Lottosim.Test.RandomQueue.strong_rand_bytes/1 is undefined (module Lottosim.Test.RandomQueue is not available)

By the time the test is actually run, the module is defined correctly and everything passes.

Moreover, the warning ceases to be shown in the following compilations, being shown only once every time I run mix clean.

Is there a way to ignore this warning?

Is there a better way of "hijacking" the function in which this warning is not shown?


Solution

  • in your mix.exs add elixirc_paths to your project config:

    def project do
      [app: :whatever,
       version: "0.1.0",
       elixir: "~> 1.3",
       elixirc_paths: elixirc_paths(Mix.env),
       build_embedded: Mix.env == :prod,
       start_permanent: Mix.env == :prod,
       deps: deps()]
    end
    
    defp elixirc_paths(:test),   do: ["lib", "test/support"]
    defp elixirc_paths(_),       do: ["lib"]
    

    and add your support module to test/support