.closest() in Capybara
Asked Answered
M

3

8

I'd like to find closest parent of an html element in cucumber. just like the .closest() function of jQuery does.

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 anybody tell me how to accomplish this using Capybara?

Cheers!

Manuel

Melmela answered 10/8, 2011 at 20:43 Comment(0)
F
2

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

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

Other than that, Capybara does not have a .closest method, but in many cases, being more creative with selectors (possibly using XPath) might do the trick.

Frogman answered 8/12, 2011 at 21:56 Comment(0)
R
2

This should be possible now using ancestor finder. Capybara 2.15.0 added ancestor method on 2017-08-04, so you should be able to do something like this now:

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

Documentation for ancestor

Revell answered 17/7, 2019 at 18:19 Comment(0)
P
1

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? fails. Please try 3.7.

Propensity answered 10/9, 2018 at 4:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.