Pass mix test filter to test_helper.exs

Can the filters from a mix test be captured by the test_helper.exs file?

I have an umbrella application in which one app has tests which run against an external API. In order for these tests to run, I need to refresh an access token from the external API. I only need to do this once before the entire test suite is run (not once per test).

It makes most sense to put this refresh function in the test_helper.exs file of the app, but I only need to run it when I’m running the tests for the external API, which are disabled by default. Is there any way to do this?

My set-up for ExternalApi app test_helper.exs file

ExUnit.configure exclude: [:external_calls]


if <some variable from mix> do
  # Put a valid access token in the config.
  refresh_token = Application.get_env(:external_api, :refresh_token)
  case ExternalApi.Token.refresh(refresh_token) do
    {:ok, resp} -> Application.put_env(:external_api, :access_token, resp.access_token)
    {:error, _} -> nil

You can get the configuration for ExUnit using ExUnit.configuration(). You could examine that configuration for the value you are looking for and then run your token refresh function when appropriate. For example,

# test_helper.exs
ExUnit.configure exclude: [:external_calls]


case ExUnit.configuration() |> Keyword.get(:include) |> Enum.member?(:external_calls) do
  true ->
    # Do refresh stuff
  _ ->

If you called the test with mix test --include external_calls, then :external_calls will be in the :include portion of the config.

The ExUnit config is a keyword list that looks like this:

  max_cases: 16,
  seed: 699143,
  autorun: false,
  capture_log: false,
  slowest: 0,
  refute_receive_timeout: 100,
  colors: [],
  formatters: [ExUnit.CLIFormatter],
  module_load_timeout: 60000,
  exclude: [:pending],
  assert_receive_timeout: 100,
  include: [],
  timeout: 60000,
  stacktrace_depth: 20,
  trace: false,
  included_applications: []

Hope that helps.

1 Like