Read more

Finding ancestors with Capybara

Michael Leimstädtner
October 20, 2021Software engineer at makandra GmbH

Modern versions of Capybara include a finder method #ancestor which allows you to find a parental element using CSS or XPath.

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

If you previously did something like this:

field.find(:xpath, './ancestor::div[contains(@class, "form-group")]')

..and prefer CSS, you may rewrite it:

field.ancestor('div.form-group')

Both versions will return the outermost matching element. Use the #order option find the closest parent:

field.ancestor('div.form-group', order: :reverse)
Posted by Michael Leimstädtner to makandra dev (2021-10-20 09:35)