我正在用Caplybara
、Cucumber
和WebDriver
进行测试,所以我看到了两个叠在一起的元素,所以我想。
- 用一种更简单的方法,是否可以知道一个元素是否在第二个元素之前
- 以一种更复杂的方式,是否可以知道一个元素是否在另一个元素之上
结构简单的
<div id="father-parent">
<p id="children-0">Firt element</p>
<p id="children-1">Second element</p>
</div>
如果您可以进行简单的内容匹配,我刚刚添加了一个新的匹配器spec/support/matchers/appear_before_matcher.rb
:
RSpec::Matchers.define :appear_before do |later_content|
match do |earlier_content|
page.body.index(earlier_content) < page.body.index(later_content)
end
end
然后像这样使用:
expect('First element').to appear_before('Second element')
如果您试图验证的是children-0正好在children-1之前,则可以使用CSS相邻的同级选择器
expect(page).to have_css('#children-0 + #children-1')
如果您只想验证子级-0是子级-1的前一个同级(不一定相邻(,您可以使用通用同级选择器
expect(page).to have_css('#children-0 ~ #children-1')
根据测试的编写方式,您还可以使用have_sibling
匹配器:
first_child = find('#children-0')
expect(first_child).to have_sibling('#children-1')
为了测试元件位置,一些驱动程序支持:below
过滤器:
expect(first_child).to have_sibling('#children-1', below: first_child)
below
是Capybara的全局过滤器之一,您也可以使用above
、left_of
和right_of
。