聚合失败

通常,期望失败会导致示例立即中止。 当您有多个独立的期望时,能够看到所有失败而不是仅第一个失败会很不错。 一个解决方案是为每个期望拆分一个单独的示例,但是如果示例的设置很慢,这会花费额外的时间并减慢速度。 aggregate_failures 提供了一种替代解决方案。 它使用块包装一组期望。 在块中,期望失败不会像平常那样立即中止; 相反,这些失败将被聚合到在块末尾引发的单个异常中,允许您查看所有失败的期望。

aggregate_failures 接受一个可选的字符串参数,该参数将在聚合的失败消息中用作标签。

RSpec::Core 扩展了此功能; 有关更多详细信息,请参阅 rspec-core 文档

注意:aggregate_failures 的实现使用线程局部变量,这意味着如果您在另一个线程中遇到期望失败,它将像平常一样中止。

aggregate_failures 中的多个期望失败都会被报告

给定一个名为“spec/aggregatedfailurespec.rb”的文件,其中包含

require 'rspec/expectations'
include RSpec::Matchers

Response = Struct.new(:status, :headers, :body)
response = Response.new(404, { "Content-Type" => "text/plain" }, "Not Found")

begin
  aggregate_failures "testing response" do
    expect(response.status).to eq(200)
    expect(response.headers["Content-Type"]).to eq("application/json")
    expect(response.body).to eq('{"message":"Success"}')
  end
rescue RSpec::Expectations::MultipleExpectationsNotMetError => e
  puts e.message.gsub(/(:in).+/, '')
  exit(1)
end

我运行 ruby spec/aggregated_failure_spec.rb

然后它应该失败,并显示

Got 3 failures from failure aggregation block "testing response":

  1) expected: 200
          got: 404

     (compared using ==)

     spec/aggregated_failure_spec.rb:9

  2) expected: "application/json"
          got: "text/plain"

     (compared using ==)

     spec/aggregated_failure_spec.rb:10

  3) expected: "{"message":"Success"}"
          got: "Not Found"

     (compared using ==)

     spec/aggregated_failure_spec.rb:11