Finding ancestors with Capybara

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

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)
Michael Leimstädtner