我有一个散列数组,我试图断言该数组有exactly a certain number个散列,其中certain order的散列值为certain key.
假设我有一系列的水果.
fruits = [
{ name: 'apple', count: 3 },
{ name: 'orange', count: 14 },
{ name: 'strawberry', count: 7 },
]
当我对hash_including
(或其别名include
)使用eq
匹配器时,断言失败.
# fails :(
expect(fruits).to eq([
hash_including(name: 'apple'),
hash_including(name: 'orange'),
hash_including(name: 'strawberry'),
])
奇怪的是,这不起作用,我总是能找到解决方法,然后继续前进,但它已经困扰了我一段时间,所以我决定这次把它贴出来.
What I'm not looking for
显然,这是可行的,但我喜欢另一种语法,因为这是这些匹配器的要点:所以我不必手动转换我的数据 struct ,并且具有更好的可读性.
fruit_names = fruits.map { |h| h.fetch(:name) }
expect(fruit_names).to eq(['apple', 'orange', 'strawberry'])
contain_exactly
和include
可以工作,但我关心的是数组的exact size和元素的order,它们未能断言.
# passes but doesn't assert the size of the array or the order of elements
expect(fruits).include(
hash_including(name: 'apple'),
hash_including(name: 'orange'),
hash_including(name: 'strawberry'),
)
# passes but doesn't assert the exact order of elements
expect(fruits).contain_exactly(
hash_including(name: 'apple'),
hash_including(name: 'orange'),
hash_including(name: 'strawberry'),
)