RSpec matcher that checks collection to include item that satisfies lambda

前端 未结 2 1399
挽巷
挽巷 2021-01-21 18:43

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.

Here is an example:



        
2条回答
  •  孤街浪徒
    2021-01-21 19:38

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

提交回复
热议问题