用于检查集合以包含满足 lambda 的项目的 RSpec 匹配器 [英] RSpec matcher that checks collection to include item that satisfies lambda
问题描述
对于如何编写 RSpec 3.2.x 规范来检查列表是否包含至少一个满足条件的项目,我有点不知所措.
I am a bit at a loss as to how to write a RSpec 3.2.x spec that checks wether a list contains at least one item that satisfies a condition.
这是一个例子:
model = Invoice.new
model.name = 'test'
changes = model.changes
expect(changes).to include { |x| x.key == 'name' && x.value == 'test' }
更改列表中也会有其他(自动)更改,因此我不想验证是否只有一个特定更改,而且我也不想依赖排序 expect(changes.first)...
所以我基本上需要一种方法来指定列表中至少有一个更改满足条件.
There will be other (automated) changes in the changes list too so I don't want to verify that there is only one specific change and I also don't want to rely on ordering expect(changes.first)...
so I basically need a way to specify that at least one change in the list satisfies the condition.
我可以这样做:
result = changes.any? { |x| x.key == 'name' .. }
expect(result).to eq(true)
但是 rspec 失败不会给我任何有意义的输出,所以我认为必须有一种内置的方法来匹配它.
But then the rspec failure would not give me any meaningful output so I thought there must be a built-in way to match this.
也欢迎提供有关如何构建测试的任何其他建议.
Any other suggestions on how to structure the test are also welcome.
要清楚 - 更改是 ChangeObject 的列表,因此我需要访问它们的 .key
和 .value
方法
To be clear - the changes are a list of ChangeObject so I need to access their .key
and .value
method
推荐答案
在 RSpec 3 中,匹配器是完全可组合的,这意味着您可以将任何实现 Ruby 的 ===
协议的对象(包括匹配器!)传递给 include
它将正常工作.Ruby 1.9 中的 Lambda 实现了 ===
协议,这意味着您可以这样做:
In RSpec 3, matchers are fully composable, which means you can pass any object which implements Ruby's ===
protocol (including a matcher!) to include
and it will work properly. Lambdas in Ruby 1.9 implement the ===
protocol, which means you can do this:
expect(changes).to include(lambda { |x| x.key == 'name' && value == 'test' })
也就是说,这不会给您一个很好的失败消息(因为 RSpec 无法生成 lambda 的描述).我不确定您的示例中 value
的来源,但如果它打算是 x.value
,您可以使用 have_attributes
(或 an_object_sharing_attributes
以获得更好的可读性)匹配器:
That said, that's not going to give you a great failure message (since RSpec has no way to generate a description of the lambda). I'm not sure where value
comes from in your example, but if it is intended to be x.value
, you could use the have_attributes
(or an_object_having_attributes
for better readability) matcher:
expect(changes).to include an_object_having_attributes(key: 'name', value: 'test')
这篇关于用于检查集合以包含满足 lambda 的项目的 RSpec 匹配器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!