如何检查RSpec测试套件中的故障?

pdg*_*137 7 ruby rspec

我正在尝试RSpec并考虑一个只有在测试套件通过时才会改变随机种子的系统.我试图在一个after(:suite)块中实现这个,它在一个块的上下文中执行RSpec::Core::ExampleGroup对象.

虽然RSpec::Core::Example有一个方法"异常"允许您检查是否有任何测试失败,但似乎没有类似的方法RSpec::Core::ExampleGroup或示例列表的任何访问器.那么,我该如何检查测试是否通过或失败?

我知道这可以使用自定义格式化程序来跟踪是否有任何测试失败,但是格式化过程影响测试的实际运行似乎是个坏主意.

Dav*_*son 6

我在RSpec源代码中探讨了一下,并发现以下内容可行.只需将此代码放入spec_helper.rb或运行测试时加载的其他文件:

RSpec.configure do |config|
  config.after(:suite) do
    examples = RSpec.world.filtered_examples.values.flatten
    if examples.none?(&:exception)
      # change the seed here
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

所述RSpec.world.filtered_examples散列示例组关联到的该组实例的阵列.Rspec具有过滤掉某些示例的功能,并且此哈希似乎仅包含实际运行的示例.


您可以设置系统的另一种方法是检查rspec进程的返回代码.如果为0,则所有测试都通过,您可以更改种子.

在shell脚本中,您可以定义一个更改种子并运行的命令:

rspec && change_seed
Run Code Online (Sandbox Code Playgroud)

如果你的项目有一个Rakefile,你可以设置这样的东西:

task "default" => "spec_and_change_seed"

task "spec" do
  sh "rspec spec/my_spec.rb"
end

task "spec_and_change_seed" => "spec" do
  # insert code here to change the file that stores the seed
end
Run Code Online (Sandbox Code Playgroud)

如果规格失败,则rake的"spec"任务将失败,并且它不会继续更改种子.