Rspec/capybara - 测试是否存在 class 或另一个 class

Rspec/capybara - test presence of a class OR another class

在我的 ruby on Rails 4.2 应用程序中,在一个页面上,我有一个条件后端规则,在 class[=16 的变化中转换为页面前端=]

<div id="content">
    <i class='<% if x=true %>glyphicon glyphicon-thumbs-down<% else> glyphicon glyphicon-thumbs-up ><% end %>' </i>
       this is the message.
</div>

如何使用 rspec 3/capybara 检查页面是否包含 class glyphicon-thumbs-down 或 class glyphicon-thumbs-up ?

我尝试了下面的代码但失败了:

it "should sheck one of the 2 classes presence" do
  expect(page).to have_css '.glyphicon-thumbs-down' || expect(page).to have_css '.glyphicon-thumbs-up'
end

我收到以下错误消息:

syntax error, unexpected tIDENTIFIER, expecting keyword_end (SyntaxError)

你的错误来自这一行:

  expect(page).to have_css 'glyphicon-thumbs-down' || expect(page).to have_css 'glyphicon-thumbs-up'

你只需要添加一些parens然后它将是有效的语法:

expect(page).to(have_css('glyphicon-thumbs-down')) || expect(page).to(have_css('glyphicon-thumbs-up'))

但这并不能解决您的问题,因为如果左侧条件失败,那么 rspec 将退出,而不是 运行 下半场。

一种可行的方法是将条件评估为布尔变量,然后将其传递给单个 rspec 期望。这样做需要使用 rspec 匹配器包中的核心 Capybara 方法 has_css to test for css presence, not have_css?

selectors = ['.glyphicon-thumbs-down', '.glyphicon-thumbs-up']
glyph_exists = selectors.any? do |selector|
  page.has_css? selector
end
expect(glyph_exists).to be true

另请注意,我已将 . 添加到选择器字符串中,这是必需的,因为它是 css class。

多个 OR-ed css 选择器可以用逗号分隔指定。尝试以下操作:

it "should sheck one of the 2 classes presence" do
  expect(page).to have_css '#content i.glyphicon-thumbs-down,#content i.glyphicon-thumbs-up'
end

(我添加了 #contenti 选择器,以便查询更具体。)

但是,我建议不要这样做,而是尝试使测试以精确定义的方式运行,并只测试规范中的单个 class。查看 this SO question 及其在测试中存根或预设随机数生成器的各种方法的答案。

首先,您正在检查 class 名称,因此您需要在 class 名称前面添加 . 使其成为 CSS class 选择器。然后,您可以使用 RSpec or 匹配器组合器

expect(page).to have_css('.glyphicon-thumbs-down').or(have_css '.glyphicon-thumbs-up')

但在检查第二个之前 Capybara.default_max_wait_time 秒,它有第一个 retrying/waiting 的缺点。如果您知道页面已经加载因此不需要 retrying/waiting

,您可以指定 0/false 等待时间
 expect(page).to have_css('.glyphicon-thumbs-down', wait: false).or(have_css '.glyphicon-thumbs-up', wait: false)

但是,使用正常的 CSS ,

检查任一元素可能没问题
 expect(page).to have_css('.glyphicon-thumbs-down, .glyphicon-thumbs-up')

也许你可以尝试使用选项 :count,在这样的 expect 方法中:

it 'should contains 2 same selector' do
  expect(page).to have_css '.some-class', count: 2
end