当我的it
块之一出现故障时,想要执行清理步骤。当所有it
块成功后,我不希望运行清理步骤。
RSpec.describe 'my describe' do
it 'first it' do
logic_that_might_fail
end
it 'second it' do
logic_that_might_fail
end
after(:all) do
cleanup_logic if ONE_OF_THE_ITS_FAILED
end
end
如何实施ONE_OF_THE_ITS_FAILED
?
答案 0 :(得分:4)
不确定RSpec是否提供了开箱即用的功能,但这可行:
RSpec.describe 'my describe' do
before(:all) do
@exceptions = []
end
after(:each) do |example|
@exceptions << example.exception
end
after(:all) do |a|
cleanup_logic if @exceptions.any?
end
# ...
end
答案 1 :(得分:0)
我在RSpec Code中略微挖掘了一些方法来修补RSpec Reporter类。把它放到spec_helper.rb中:
class RSpecHook
class << self
attr_accessor :hooked
end
def example_failed(example)
# Code goes here
end
end
module FailureDetection
def register_listener(listener, *notifications)
super
return if ::RSpecHook.hooked
@listeners[:example_failed] << ::RSpecHook.new
::RSpecHook.hooked = true
end
end
RSpec::Core::Reporter.prepend FailureDetection
当然,如果您希望根据当前运行的规范执行不同的回调,它会变得更复杂。
无论如何,通过这种方式,您不必将测试代码与异常或计数器混淆以检测故障。