How to get XPath of Capybara's query
Have you ever found yourself in a situation, where you were trying to do something like e.g. click_link 'Approve'
and Capybara was not able to find that element on the page despite the fact that itâs quite clearly visible, and you were asking yourself âwhat the heck is it searching for then?â. Or maybe your find(sth)
is failing and you think itâs a bug in the Capybara đ±
Worry no more! Now you can easily check generated XPath used by Capybara*. In most cases, find(*args, **options)
translates to:
Capybara::Queries::SelectorQuery.new(*args, session_options: current_scope.session_options, **options).xpath
E.g. to see XPath for click_on 'Approve'
:
Capybara::Queries::SelectorQuery.new(:link_or_button, 'Approve', session_options: current_scope.session_options).xpath
And XPath for find('tbody > tr > td:nth-child(2)')
:
Capybara::Queries::SelectorQuery.new('tbody > tr > td:nth-child(2)', session_options: current_scope.session_options).xpath
Then you can copy that XPath to the Chromeâs console and test it with $x('xpath')
.
* Presented solution doesnât work with some types of more complicated queries, e.g. find('a', text: 'APPROVED')
actually uses CSS selector instead of the XPath, and then filter results using Capybara::Result
. You can check type of the selector used using .selector.format
on your selector query.