Rails Capybara RSpec XPath CSS选择器仅使用子项

时间:2016-09-13 05:30:56

标签: ruby-on-rails xpath rspec capybara

我使用Cucumber和RSpec检查黄色的div是否具有类card-selected

asdf

我写的代码是

node = page.find(:css, '.card-selected')
#<Capybara::Node::Element tag="div" path="//HTML[1]/BODY[1]/DIV[3]/DIV[1]/DIV[2]/DIV[1]/DIV[2]/DIV[1]/DIV[1]/DIV[1]/DIV[7]">

如果我在Chrome中复制已恢复的XPath,我会按预期选择黄色div。

问题在于查询节点的CSS属性。据我了解,这不是预期的行为:

# Checking for current node contents
node.has_css?('.card-selected')
false

node.has_selector?(:css, '.card-selected')
false

node.has_css?('.card-contents')
true

但是,如果我查询节点的父节点

# Checking for parent node contents
node.find(:xpath, '..').has_css?('.card-selected')
true

node.find(:xpath, '..').has_css?('.card-deselected')
true

node.find(:xpath, '..').has_css?('.card-contents')
true

从这种行为来看,has_css?方法似乎只检查子内容,而不是节点本身。我无法找到解决方法,因为查询父级会使匹配过于复杂。

我在这里不理解什么?

1 个答案:

答案 0 :(得分:1)

您预期会看到的行为 - 查找程序在当前范围元素和has_xxx中查找?方法是一样的。它们检查当前范围元素是否包含与传递的选择器匹配的元素。你想要的是matches_selector?

node.matches_selector?(:css, '.card-selected') # the :css is optional if it's the default selector type

或期待表格

expect(node).to match_css('.card-selected')