Read more

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

Henning Koch
October 05, 2021Software engineer at makandra GmbH

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".

Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

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

Posted by Henning Koch to makandra dev (2021-10-05 09:57)