elixirelixir-mixex-unit

Can I split helper modules into different files using ExUnit with Mix?


A couple failed attempts and the documentation here leads me to believe that I have to either define helper modules in test/test_helper.exs or in one of the other test/*.exs files nested under a module (that use ExUnit.Case) in my mix project. Is there a way to define these modules in their own files so that tests can use them, without cluttering up test/test_helper.exs or putting them under lib/?


Solution

  • In your mix.exs file you define different paths for different environments in the project declaration (inside Mix.Project.project/0 callback, key elixirc_paths:

    defmodule MyApp.MixProject do
      use Mix.Project
    
      def project do
        [
          ...
          elixirc_paths: elixirc_paths(Mix.env()),
          ...
        ]
      end
    

    Then you provide different clauses for different environments:

    defp elixirc_paths(:test), do: ["lib", "test/helpers"]
    defp elixirc_paths(_), do: ["lib"]
    

    The paths above will be added to what Elixir compiles and all the code in test/helpers dir will become available in the runtime when running the project in test environment only.