无法确定测试是否在 after hook 中失败

Unable to detrmine if a test failed in an after hook

我尝试在测试失败时做一些额外的事情。

这是失败的测试:

it 'fails' do
  expect(1213).to eq('123456')
end

将以下代码添加到 spec_helper:

RSpec.configure do |config|
  config.after(:each) do |example|
    if example.exception
      puts 'Do something'
    end
  end

结果如下:

expected: "123456" got: "1213" (compared using ==)

1 example, 1 failure, 0 passed

Finished in 2 seconds

示例中的异常保持为零,我不明白wy。有没有其他方法可以在测试失败后获得额外的代码?

这是答案(以及解决方案的想法)https://github.com/rspec/rspec-core/issues/2011#issuecomment-114669886:

Anyhow, the status is not set until AFTER the after hooks run. That is intentional because the after hook is itself part of the example, and if an exception occurs in the after hook we'll set the status of the example to :failed. after hooks are great for cleanup/teardown logic but isn't intended for observing the status of examples. Instead, I recommend you use a formatter for that...

代码应该可以完美运行,您应该在 "F" 打印到 STDOUT 之前看到 "Do something",如下所示:

Randomized with seed 3598
Do something
F

Failures:

  1) Blah#blah fails
     Failure/Error: expect(1213).to eq('123456')

       expected: "123456"
            got: 1213

       (compared using ==)
     # ./spec/index_spec.rb:9:in `block (2 levels) in <top (required)>'

Finished in 0.01617 seconds (files took 0.09568 seconds to load)
1 example, 1 failure, 0 passed

还要注意你用的是哪个rspec版本,你的测试报告和我的不一样。我的是 v3.8