Bylaw. Credo. Check. Testing. PreferSelectorAssertionsForHtml
(bylaw_credo v0.3.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
Prefer selector-based assertions over comparisons against serialized HTML with multiple selector-relevant attributes.
Examples
Avoid:
assert html =~ ~s(<button id="save" phx-click="save">Save</button>)Prefer:
assert has_element?(view, "#save[phx-click=save]")Notes
HTML attribute order has no semantic meaning, and serializers may emit the same attributes in a different order. Comparing serialized HTML can therefore produce flaky tests even when the DOM is unchanged. Selector-based assertions express the intended DOM contract without coupling tests to serialization details.
The check reports direct assert and refute comparisons using ==, ===,
!=, !==, or =~ when a string operand contains an opening HTML tag with
at least two phx-*, data-*, aria-*, id, or class attributes.
Path exclusions are matched against the source filename and are intended for snapshots or tests where exact serialization is deliberately the contract.
The check uses static AST analysis, so dynamically constructed strings and macro-expanded assertions may fall outside its signal.
Options
Configure options in .credo.exs with the check tuple:
%{
configs: [
%{
name: "default",
checks: [
{Bylaw.Credo.Check.Testing.PreferSelectorAssertionsForHtml,
[excluded_paths: ["test/snapshots/"]]}
]
}
]
}:excluded_paths- Paths containing any configured string are skipped.
Check-Specific Parameters
Use the following parameters to configure this check:
:excluded_paths
Paths containing any configured string are skipped. Use this for snapshots or tests that intentionally verify exact serialization.
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.