/ Bit by bit / posts

Testing Elixir Without Starting Your App

Jun 6, 2021

By default, mix test starts the project’s applications as part of the task. While this usually is helpful, sometimes not starting your application is necessary, e.g., when your application’s supervisor starts up singletons that may interfere testing.

Luckily, mix test supports the command line option --no-start to skip starting the applications after compilation. To make this the “default” behavior, create the test alias to “override” the original in mix.exs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
defmodule Sample.MixProject do
  use Mix.Project

  def project do
    [
      app: :sample,
      aliases: aliases(),
      # ... rest omitted for brevity ...
    ]
  end

  defp aliases do
    [
      test: "test --no-start"
    ]
  end
end

Doing this alone is not enough: you still need to start the applications that yours rely on, e.g., the standard library, Elixir itself. To find out the applications yours depends on, retrieve the list with Application.spec/2 and start them in test_helper.exs:

1
2
3
4
5
6
7
# in test_helper.exs

for app <- Application.spec(:sample, :applications) do
  Application.ensure_all_started(app)
end

ExUnit.start()