Read more

Spreewald, Cucumber: Selector for the nth element

Felix Eschey
October 17, 2023Software engineer at makandra GmbH

The recommended additional setup Show archive.org snapshot of the spreewald gem Show archive.org snapshot , a useful set of cucumber steps, includes adding a file for defining custom selectors which can be used as prose within steps:

When I follow "Edit" within the controls section
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Where the controls section can be any arbitrary defined css selector within selectors.rb


Often it can be useful to select the nth element of a specific selector. Luckily, this can be achieved by dynamic selectors too with the following code:

# ./features/support/selectors.rb

module HtmlSelectorsHelpers
  def selector_for(locator)
    case locator
    ... # when cases for individual selectors
    
    when /\Athe (\d+)(st|nd|rd|th) (role|showtime) fields?\z/
      ".nested-fields .nested-fields--form:nth-of-type(#{$1})"
    end
  end
end

World(HtmlSelectorsHelpers)

nth-of-type matches by counting the actual HTML-tag

Using :nth-of-type Show archive.org snapshot like this, might not work as you expect, as it only cares about the HTML-Tag type. Example Show archive.org snapshot . This might lead to breaking tests when your html changes.

Once browser support Show archive.org snapshot is fulfilled prefiltering nth-child selector will be an alternative Show archive.org snapshot as you can see in this example Show archive.org snapshot .

This will now allow us to write cucumber steps like so:

Scenario: Example scenario 
  Given ...
    
  When I fill in "Character" with "Kaiser" within the 1st role fields
    And I select "Moon" from "Movie" within the 1st role fields
    And I click on "Save"
  Then the "Movie" field should contain "Moon" within the 1st role fields
Posted by Felix Eschey to makandra dev (2023-10-17 13:03)