Capybara can find links and fields by their [aria-label]

Posted Over 2 years ago. Visible to the public. Repeats.

Sometimes a link or input field has no visible label. E.g. a text field with a magnifying glass icon 🔎 and a "Search" button does not really need a visible label "Query".

For accessibility Show archive.org snapshot reasons it is good practice to give such a field an [aria-label] attribute:

<input type="search" aria-label="Search contacts">

This way, when a visually impaired user focuses the field, the screen reader will speak the label text ("Search contacts").

Info

Without an [aria-label] attribute screen readers will announce the field by its element type. In the example above (if no [aria-label] would be provided) it would speak something like "Search input".

Configuring Capybara to use [aria-label]

Capybara will not by default find an input field by its [aria-label] attribute. However, you can configure it to do so:

fill_in 'Search contacts', with: 'foo' # => raises "Unable to find field 'Query'"

Capybara.enable_aria_label = true # enable [aria-label] support for field finders

fill_in 'Search contacts', with: 'foo' # => fills in the query "foo"

Also see An auto-mapper for ARIA labels and BEM classes in Cucumber selectors

Henning Koch
Last edit
About 2 years ago
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2021-10-05 07:57)