Home > Software design >  Why can't I import test modules directly into other tests in elixir
Why can't I import test modules directly into other tests in elixir

Time:10-17

I spent days trying to figure out how to import my test modules into a master test module so I could run them synchronously and I finally found my solution at the link below:

Importing test code in elixir unit test

My question is - WHY does this have to be a work-around? Why won't elixir allow me to directly alias or import my test modules into my test_suite.exs?

CodePudding user response:

TLDR:

  • It doesn't have to be a workaround :)
  • Elixir just relies on the :elixirc_paths variable, defaulting to ["lib"], to determine where to find files to be compiled.

A standard way to do this, which is done by default by mix phx.new if you work with Phoenix for instance, is to add the following to your mix.exs:

  def project do
    [
      ...,
      elixirc_paths: elixirc_paths(Mix.env())
    ]
  end

  # Specifies which paths to compile per environment.
  defp elixirc_paths(:test), do: ["lib", "test/support"]
  defp elixirc_paths(_), do: ["lib"]

Then every module defined in a .ex file (not .exs!) within test/support/ will be compiled when running your test suite.

  • Related