Rspec 的详细 [​​=10=] 匹配器错误

Verbose parent/child matcher errors for Rspec

给定以下代码,当我遇到故障时,我希望同时显示父级和子级差异。目前,如果我在子级别上存在不匹配,我只会得到反馈,即我的父级不包含预期的子级,而不是我实际的子级。:

RSpec::Matchers.define :have_categories do |expected|
  match do |actual|
    expected.each do |ex|
      lines = ex.map do |ex_line|
        an_instance_of(Model::SubCategory).and(have_attributes(ex_line))
      end
      expect(actual.categories).to include(an_instance_of(Model::Category).and(
                                             have_attributes(sub_categories: contain_exactly(*lines))))
    end
  end
end

基本上,您需要实现 failure_message 方法来格式化预期的错误消息,在这里您可以创建一个您希望看到的差异字符串:

RSpec::Matchers.define :have_categories do |expected|
  match do |actual|
    expected.each do |ex|
      lines = ex.map do |ex_line|
        an_instance_of(Model::SubCategory).and(have_attributes(ex_line))
      end
      expect(actual.categories).to include(an_instance_of(Model::Category).and(
                                         have_attributes(sub_categories: contain_exactly(*lines))))
    end

    failure_message do |actual|
      # here you are able to use both `actual` and `expected`
      # to create your error message
    end
  end
end

请提供有关您的域的更多信息,以便我可以帮助您准备正确的错误消息。

希望对您有所帮助!