Temporarily changing app config in tests

almirsarajcic

almirsarajcic

11 months ago

0 comments

When testing functionality that depends on application configuration, you can temporarily set specific config values and ensure they’re restored afterward.

Use on_exit/1 to guarantee cleanup after the test run, preventing global state pollution:

defmodule MyApp.ProcessorTest do
  use MyApp.DataCase, async: false

  setup do
    on_exit(fn ->
      Application.put_env(:my_app, :processor, MyApp.MockProcessor)
    end)

    Application.put_env(:my_app, :processor, MyApp.FileProcessor)

    :ok
  end

  # tests
end

Note async: false - changing application config affects global state, so tests must run in isolation to avoid interfering with each other.

The cleanup function runs after the test completes, even if it crashes or fails, keeping your test suite stable.

Upgrade: If you want the whole test file to stay async: true, there’s a process-local approach that avoids mutating global state entirely — see Override config in async tests.

Comments (0)

Sign in with GitHub to join the discussion