【问题标题】:Make specs pending conditionally有条件地使规范待定
【发布时间】:2020-10-20 12:09:03
【问题描述】:

在我的应用中,我有时会使用这样的迭代来编写测试:

%w[one two three].each do |number|
  it 'is going to fail under several circumstances' do
    expect(someting_from(number))
  end
end

而且我知道,有时对于数组中的多个实例,我迭代此规范可能会暂时失败,但几天后会好起来的,所以我想有条件地跳过它们,使用内部 RSpec 挂起机制,所以我会收到通知当这个规范停止失败时。有没有办法做到这一点?

【问题讨论】:

  • “我想有条件地跳过它们”——基于什么?如果 RSpec 被告知跳过它们,您如何获得通知它们停止失败?
  • 顺便说一句,我不建议编写代码来隐藏或消除测试失败。如果您习惯于失败的测试,您可能会忽略或忽略实际问题。而是解决根本原因。找出为什么您的测试在某些日子失败但在其他日子通过。然后从你的测试中消除这个方面。最好有一个可靠的测试套件。

标签: ruby rspec rspec3


【解决方案1】:

可以将pending inside an example 与if 一起使用。就像这样:

%w[one two three].each do |number|
  it 'is going to fail under several circumstances' do
    pending("It's not your fault") if we_know_about_this(number)
    expect(someting_from(number))
  end
end

【讨论】:

  • 您也可以不首先定义测试,方法是将定义本身包装在if 中。这取决于您是想“跳过”它们,还是完全忽略它们。
  • 正如我在问题中所说,我希望收到通知,这些测试不再失败,skip 是实现此目的的完美方式。不定义它们不会给我这些信息。而且我们都知道,大多数被注释掉的测试,标有xit 或类似这样的东西很可能永远不会再执行,因为没有人会回到它们=)
  • 哦,我知道有时您希望它们显示为明确跳过。我只是在解释如何完全跳过这些步骤如果这对你更有效。
【解决方案2】:

我相信你不需要他们跳过,你可以改变对特定项目的期望。当测试被修复时,您的测试用例将失败并且您会收到通知:

%w[one two three].each do |number|
  it 'is going to fail under several circumstances' do
    if number == 'two'
      expect(something_from(number)).to be false
    else
      expect(something_from(number))
    end
  end
end

当something_from('two') == false

...

Finished in 0.01532 seconds (files took 0.80331 seconds to load)
3 examples, 0 failures

当something_from('two') == true

.F.

Failures:

  1) is going to fail under several circumstances
     Failure/Error: expect(something_from(number)).to be false
     
       expected false
            got true
     # ./spec/conditional_spec.rb:7:in `block (3 levels) in <top (required)>'

Finished in 0.0175 seconds (files took 0.79527 seconds to load)
3 examples, 1 failure

Failed examples:

rspec ./spec/conditional_spec.rb[1:2] # is going to fail under several circumstances

UPD

使用pending 在特定测试停止失败时使测试失败:

%w[one two three].each do |number|
  it 'is going to fail under several circumstances' do
    if number == 'two'
      pending
      expect(something_from(number))
    else
      expect(something_from(number))
    end
  end
end

【讨论】:

  • 你不推荐使用rspec的skip吗?或者你会建议在什么情况下使用它?
  • 您提到了可以修复测试的通知。在我的解决方案中,通知将非常明确。使用skip 由你决定。
  • skip 还会在跳过的测试停止失败并开始通过时显示通知。你说你不建议跳过。为什么?
  • 我没说不推荐skip。使用skip,您的测试始终保持绿色,据我所知,当测试用例停止失败时,只有pending 会导致测试失败。
  • 我在答案中添加了一个带有pending 的示例。
猜你喜欢
  • 1970-01-01
  • 2021-03-22
  • 2020-05-13
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-11
  • 1970-01-01
相关资源
最近更新 更多