Xpath adventures!
I was using a chunk of code that I found to be rather brittle for testing Xpath with Capybara in a ruby on rails integration test. Originally I was just calling click_link
on the first link within the .body
tag.
The problem is that’s really brittle. Any other links put in there before that will mess up the process. Also, if I make that page a partial so I can reuse that particular list on other pages, then my test is broken.
So my practice now is to add a class or div to the top of all partials or pages even if I have the body & nothing else is in that page.
An example:
The partial _campaign.html.haml
would have a .campaigns
at the top wrapping it. Then my html/css parsing with Xpath would be `.campaigns` to get into the section of the list I want to affect.
For my purposes that’s enough. If you want to go deeper though – as you have more elements inside & need to be selective, then you would add more path hierarchy … .campaigns/.list-group/.list-group-item[1]
… with the last [1]
being select the first item in the list group.
Xpath best practices is to not stack too many or any nested items so they use within
. Still, probably best to only use two within
‘s one to grab the first unique class/div name & the next to grab the last div or element before running the method against the result.
- Instead the previous campaigns example, using the
within
would be combined with something else….
within('.campaigns') do
first('.list-group-item').click_link('Join')
end
Also, as a bonus I had to figure out the calls for using spaces in the names/titles. There are two methods I like.