Search code examples
rubyselenium-webdrivercapybara

How do capybara ancestor and sibling instance methods actually work?


Typically when I had to find siblings, I had to do this:

find('#child').find(:xpath, '..').find(#some-other-child-from-this-parent)

Does using sibling replace this entire line?

Does ancestor replace the call to traverse upwards in the xpath selector?

How "far down" do these instance methods navigate?

Thank you


Solution

  • Capybaras ancestor and sibling methods are called on an element and take the same parameters as find. They are implemented by locating all elements that match the passed in parameters and intersecting that with the set of ancestor or sibling elements respectively. From your example finding a sibling of the element with id of 'child' could be like

    find('#child').sibling('.some_class') 
    

    which would return an element with the class some_class which is a sibling of the element with id of child. ancestor works the same way but looks up the document tree at all the elements ancestors.

    td_element.ancestor('table')
    

    would return the table element which is the ancestor of the previously found td element