RSpec 检查集合以包含满足 lambda 的项目的匹配器

RSpec matcher that checks collection to include item that satisfies lambda

关于如何编写 RSpec 3.2.x 检查列表是否包含至少一项满足条件的规范,我有点不知所措。

这是一个例子:

model = Invoice.new
model.name = 'test'
changes = model.changes
expect(changes).to include { |x| x.key == 'name' && x.value == 'test' }

更改列表中也会有其他(自动)更改,所以我不想验证是否只有一个特定的更改,我也不想依赖排序 expect(changes.first)... 所以我基本上需要一种方法来指定列表中的至少一个更改满足条件。

我可以这样做:

result = changes.any? { |x| x.key == 'name' .. }
expect(result).to eq(true)

但是 rspec 失败不会给我任何有意义的输出所以我认为必须有一个内置的方法来匹配它。

也欢迎就如何组织测试提出任何其他建议。

编辑:要清楚 - 更改是 ChangeObject 的列表,所以我需要访问它们的 .key.value 方法

试试这个

expect(changes).to be_any{ |x| //logic to match }

在RSpec 3中,matchers are fully composable,这意味着您可以将任何实现Ruby的===协议(包括匹配器!)的对象传递给include,它将正常工作。 Ruby 1.9 中的 Lambda 实现了 === 协议,这意味着您可以这样做:

expect(changes).to include(lambda { |x| x.key == 'name' && value == 'test' })

就是说,这不会给您带来很大的失败消息(因为 RSpec 无法生成 lambda 的描述)。我不确定 value 在你的例子中来自哪里,但如果它是 x.value,你可以使用 have_attributes(或 an_object_having_attributes 以获得更好的可读性)匹配器:

expect(changes).to include an_object_having_attributes(key: 'name', value: 'test')