Capybara: Accessing the parent of an element

Updated . Posted . Visible to the public. Repeats.

If you already selected an element and want to get its parent, you can call find(:xpath, '..') on it.

To get the grand-parent element, call find(:xpath, '../..').

Example

Find a link which contains a twitter icon and check that it links to the correct page:

<a href="http://twitter.com/">
  <i class="icon is-twitter"></i>
</a>
link = page.find("a .icon.is-twitter").find(:xpath, '..')
expect(link[:href]).to eq("http://twitter.com/")

About XPath

There is a good overview on XPath syntax on w3schools Show archive.org snapshot . But as XPath expressions can get quite complex and hard to understand for fellow developers, it's best to keep them short and simple.

Judith Roth
Last edit
Felix Eschey
Keywords
ruby, testing, e2e, integration, test
License
Source code in this card is licensed under the MIT License.
Posted by Judith Roth to makandra dev (2017-09-22 12:09)