Temporarily changing app config in tests

almirsarajcic

almirsarajcic

Created 8 hours ago

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.