RSpec matcher that checks collection to include item that satisfies lambda

送分小仙女□ 提交于 2019-12-02 04:06:18

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' })

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')

Try this

expect(changes).to be_any{ |x| //logic to match }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!