0

I need to be able to execute code on part of the page within an ancestor of an unique element.

I have the following code:

find('div', text: 'text').ancestor('ancestor').find('desired').click

and I'm sometimes getting the following error on the second or third appearance of the above line in a test case:

Ambiguous match, found 2 elements matching visible css "desired" 
within #<Capybara::Node::Element tag="html" path="/HTML">

This also happens more regularly when executing the following:

element = find('div', text: 'text').ancestor('ancestor')
element.find('desired').click
expect(element).to have_content('stuff')

I can not use first or all since I think they are the cause of stale element reference error on a dynamic page. The stale element error disappears by using this.

In the second example reinitiating element after click does not help.

I don't know how to use ancestor with within and even then I would have to use within every time I switch between this element and root, which is often.

Note that this is a potential duplicate of a unanswered question, but I created a new question because of the much newer version of capybara (I use 3.15.0) this is happening in. The issue is happening both locally and remote in this case.

EDIT: I found an example that always replicates the error:

element = find('example').ancestor(:css, '.ancestor')
element.find(:css, '.marked').click
puts element.path
expect(element).to have_no_css('.marked')

The path on line 3 will be correctly printed to console but the example will fail with the above error. If I put sleep 2 between puts ... and expect ... there will be no error. I suppose this is not expected capybara behaviour?

SugarOnBacon
  • 115
  • 7
  • This seems like a bug in Capybara with the reloading behavior of ancestor elements. What exactly does clicking on the '.marked' element do? – Thomas Walpole Jul 24 '19 at 15:39
  • Makes some requests and after they are done removes the ccs '.marked'. So for as far as Capybara is concerned, executes some javascript, and removes '.marked' css after a delay. But it seems you already found the cause of this problem. – SugarOnBacon Jul 24 '19 at 18:31
  • FYI: This should now be fixed in the Capybara master branch if you want to give that a try – Thomas Walpole Jul 25 '19 at 22:58

1 Answers1

1

Update: The original issue should be fixed in the Capybara master branch as of 7/25/2019

I've confirmed there is a bug in Capybaras ancestor method if the node originally returned ever needs to be reloaded. You can temporarily work around that by using xpath queries rather than ancestor with something like

element = find('example').find(:xpath, './/ancestor::*'. class: 'ancestor')

Thomas Walpole
  • 48,548
  • 5
  • 64
  • 78