修改黄瓜步骤定义以提供更有用的输出



编写了一个步骤定义,该定义使用集合中的rsspec检查CSS元素。如果一个期望失败,整个场景就会爆炸,我甚至没有得到关于每个CSS元素是否存在的唯一反馈(不幸的是,要么全有要么全无!我不想要这样)

我有以下代码:

Then(/^I should see the following css selectors:$/) do |table|
  css_selectors = table.raw
  css_selectors.each do |selector|
    browser.element(:css=>selector.to_s).exists?.should be_true
  end
end

如果我测试一个大的元素列表,即:

Then I should see the following css selectors:
  |input#foo|
  |.bar     |
  |h#baz    |
  |span.batz|

如果不存在任何元素,我就会遇到问题。帮助

您可以向失败添加一条自定义消息,其中包括失败的选择器。这是通过向should方法传递第二个参数来完成的:

Then(/^I should see the following css selectors:$/) do |table|
  css_selectors = table.raw
  css_selectors.each do |selector|
    css_selector = selector[0].to_s
    browser.element(:css=>css_selector).exists?.should be_true, "Element not found: #{css_selector}"
  end
end

这将给出一条错误消息,如:

Element not found: input#foo (RSpec::Expectations::ExpectationNotMetError)

如果您还想确保所有选择器都运行,则必须运行每个选择器,收集结果并对结果组执行断言。

Then(/^I should see the following css selectors:$/) do |table|
  css_selectors = table.raw
  # Collect any failed selectors
  failed_selectors = []
  css_selectors.each do |selector|
    css_selector = selector[0].to_s
    failed_selectors << css_selector unless browser.element(:css=>css_selector).exists?
  end
  # Check that none of the selectors failed
  failed_selectors.should be_empty, "The following elements were not found #{failed_selectors.join(', ')}"
end

在场景中是否可以不调用fail

请参阅:如何强制黄瓜场景失败?

最新更新