Spreewald, Cucumber: Selector for the nth element

Posted . Visible to the public.

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

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
Felix Eschey
Last edit
Felix Eschey
Keywords
n-th
License
Source code in this card is licensed under the MIT License.
Posted by Felix Eschey to makandra dev (2023-10-17 11:03)