I’m trying to chain find methods in Capybara and not having much luck. I would expect the second find to only look for text in the output of the first find. However, the second find searches the entire document.
element = page_foo.find('.bar') element.find('div', :text => "name") => All divs with the text "name" on the page.
A solution using xpath was described here:
capybara – Find with xPath is leaving the within scope
However, I am not too familiar with xpath and hope to find a way to work around it.
My BMW 5-SERIES GRAN TURISMO.My BMW 5-SERIES GRAN TURISMO.
element = page_foo.find('[data-id="tabMeListProducts"]') =># element.find('div', :text => "My BMW 5-SERIES GRAN TURISMO.") =>Capybara::Ambiguous: Ambiguous match, found 2 elements matching css "div" with text "My BMW 5-SERIES GRAN TURISMO."
As you can see from the example above the second find’s scope is the entire page and is not contained within the element passed in by the initial find.
I would expect the find to only look within the div contained in the variable “element”.
I remember nested find calls working in past versions of Cucumber or Capybara. However, things change with every version. Regardless, your example is more easily handled with nested CSS expressions instead of relying on multiple finds.
page_foo.find('[data-id="tabMeListProducts"] div', :text => "My BMW 5-SERIES GRAN TURISMO.")
If there are multiple occurrences, I would use
and run my own Ruby checking logic on the collection.
usually works as an alternative (no need to call
with it as one response mentioned, you can add CSS directly next to it):
within '[data-id="tabMeListProducts"]' do element.find('div', :text => "My BMW 5-SERIES GRAN TURISMO.") end
Lastly, if you insist on using nested find calls, try doing them on the same Ruby line as mentioned by the Capybara documentation:
It’s possible it’s lazy fetched, but activates at the end of a Ruby line (through meta-programming checks for line number).
If all else fails, open a GitHub issue: http://www.rubydoc.info/github/jnicklas/capybara/Capybara/Node/Finders#find-instance_method
You’d be surprised by how fast people respond to you, but I have a feeling one of the solutions above will just work.
Good luck! I understand this can be a frustrating issue, but I’m sure you got it!