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 book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
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)