elixirex-unit

In Elixir, placing test files alongside their related modules


Is it possible in elixir to have my test modules in the same directory as the modules they are testing?

A typical Elixir project has a structure like this:

project
|-- lib
|   `-- my_module.ex
`-- test
    |-- my_module_test.exs
    `-- test_helper.exs

When writing node projects I like to have my test modules next to the modules they are testing. This is easily configarable using tools like Jest:

project
|-- lib
|   |-- my_module.ex
|   `-- my_module.test.exs
`-- test
    `-- test_helper.exs

Is it possible to have a similar setup in Elixir/Exunit?


Solution

  • OK, I’ll put it as an answer for the sake of future visitors.

    Mix documentation explicitly states

    Invoking mix test from the command line will run the tests in each file matching the pattern *_test.exs found in the test directory of your project.

    It looks like ExUnit authors strongly discourage developers to put tests somewhere else. As @harryg discovered, it’s still possible, though. project settings have test_paths variable that is checked for where tests are to be found (and test_pattern for the pattern,) defaulted to "test" and "*_test.exs" respectively.

    To reset it to some other value, simply update the project callback adding these two lines:

    
          def project do
            [
              app: @app,
              version: @version,
              elixir: "~> 1.6",
              start_permanent: Mix.env() == :prod,
              ...
              test_paths: ".",
              test_pattern: "*_test.exs" # or something else
            ]
          end