.closest () in Capybara

I would like to find the closest parent of the html element in the cucumber. like the .closest () jQuery function.

this is my (pseudo) code:

aspect = find('.dropdown li:contains('+selector+')') dropdown = aspect.closest('.dropdown') #<-- the closest() function does not exist if not aspect.hasClass('.selected') dropdown.click sleep 1 aspect.click end 

Can someone tell me how to do this with Capybara?

Hurrah!

Manuel

+7
source share
3 answers

This is not a universal solution, but if all you want to do is click an element, I would suggest using jQuery directly:

 page.execute_script('$(...).closest(...).click()') 

In addition, Capybara does not have a .closest method, but in many cases a more creative approach with selectors (possibly using XPath) can do the trick.

+1
source

Try this.

 module CapybaraNodeElementExtension def closest(*args) parent = first(:xpath, './/..', wait: false) until parent.matches_selector?(*args) # return nil if not found if parent.matches_selector?(:xpath, '/HTML') parent = nil break end parent = parent.first(:xpath, './/..', wait: false) end parent end end Capybara::Node::Element.send(:include, CapybaraNodeElementExtension) 

This code did not work with version 2.18. matches_selector? out of order. Please try 3.7.

0
source

This should be possible now using the ancestor finder. Capybara 2.15.0 (I suppose) added the ancestor method on July 10, 2017, so you should do something like this now:

  aspect = find('.dropdown li:contains('+selector+')') dropdown = aspect.ancestor('.dropdown') 
0
source

Source: https://habr.com/ru/post/894763/


All Articles