RSpec 匹配来自 VCR 的哈希数组

RSpec match array of hashes from VCR

在我的 VCR 盒式磁带的结果中,我得到了一个哈希数组:

[{
  'key' => 'TP-123',
  'status:' => 'test'
},
{
  'key' => 'TP-124',
  'status:' => 'test'
},
{
  'key' => 'TP-125',
  'status:' => 'test'
},
{
  'key' => 'TP-126',
  'status:' => 'test'
},
]

我想检查是否有 'key' => 'TPFJT-41'

的散列

expect(fetcher).not_to include('key' => 'TPFJT-41')

它似乎没有遍历整个哈希数组,但它采用第一个值 - 当我将其更改为:

expect(fetcher).not_to include('key' => 'TP-126')

它会通过

it seems to not iterate through the whole array of hashes but it takes the first value

没有。它不仅仅采用第一个值。它确实会迭代。问题是您期望 include 匹配器做它 而不是 实际上做的事情。它不够聪明,无法查看嵌套对象 :) 当应用于数组时,它只是检查数组中是否存在 object

因此,在您的情况下,它会检查散列 {'key' => 'TPFJT-41'} 是否存在。显然,它没有,所以你否定的期望总是绿色的(但规范被打破了)。

修复它的方法之一是在检查之前转换结果。例如,像下面这样的东西应该可以工作:

expect(fetcher.map { |h| h['key'] }).not_to include('TPFJT-41')