Bylaw.Credo.Check.Testing.NoGlobalStateInTests (bylaw_credo v0.1.0-alpha.1)

Copy Markdown View Source

Basics

This check is disabled by default.

Learn how to enable it via .credo.exs.

This check has a base priority of higher and works with any version of Elixir.

Explanation

Avoid reading or mutating global application and system environment state from tests.

Examples

Avoid:

  test "uses config" do
    Application.put_env(:my_app, :feature_enabled?, true)
    assert Feature.enabled?()
  end

Prefer:

  test "uses config" do
    assert Feature.enabled?(%{feature_enabled?: true})
  end

Notes

Application and system environment are shared process-wide state. Tests that read or mutate that state can race with each other when the suite runs concurrently, especially when a test forgets to restore a value.

Prefer passing dependencies or configuration explicitly. If a test needs a substitute implementation, use a behaviour-backed module or mock that is scoped to the test process.

Path exclusions are matched against the source filename and are intended for generated files or temporary migration areas.

The check uses static AST analysis, so dynamic code generation and macro-expanded code may fall outside its signal.

Options

Configure options in .credo.exs with the check tuple:

%{
  configs: [
    %{
      name: "default",
      checks: [
        {Bylaw.Credo.Check.Testing.NoGlobalStateInTests,
         [
           excluded_paths: ["test/support/"]
         ]}
      ]
    }
  ]
}
  • :excluded_paths - Paths containing any configured string are skipped. Use this for test support files that intentionally own global test configuration.

Usage

Add this check to Credo's checks: list in .credo.exs:

%{
  configs: [
    %{
      name: "default",
      checks: [
        {Bylaw.Credo.Check.Testing.NoGlobalStateInTests, []}
      ]
    }
  ]
}

Check-Specific Parameters

Use the following parameters to configure this check:

:excluded_paths

Paths containing any configured string are skipped. Use this for test support files that intentionally own global test configuration.

This parameter defaults to [].

General Parameters

Like with all checks, general params can be applied.

Parameters can be configured via the .credo.exs config file.