在Capybara的.closest()

问题描述 投票:6回答:2

我想在黄瓜中找到最接近html元素的父级。就像jQuery的.closest()函数一样。

这是我的(伪)代码:

  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

任何人都可以告诉我如何使用Capybara完成这个任务?

干杯!

曼努埃尔

jquery capybara closest
2个回答
1
投票

这不是一个通用的解决方案,但如果您只想单击该元素,我建议您直接使用jQuery:

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

除此之外,Capybara没有.closest方法,但在很多情况下,选择器(可能使用XPath)更具创造性可能会有所帮助。


0
投票

试试这个。

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)

此代码不适用于版本2.18。 matches_selector?失败了。请尝试3.7。

© www.soinside.com 2019 - 2024. All rights reserved.