我有一个散列数组,我试图断言该数组有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_exactlyinclude可以工作,但我关心的是数组的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'),
)

推荐答案

看起来你只需要用match

fruits = [
  { name: 'apple', count: 3 },
  { name: 'orange', count: 14 },
  { name: 'strawberry', count: 7 },
]

expect(fruits).to match([
  include(name: 'apple'),
  include(name: 'orange'),
  include(name: 'strawberry'),
])

如果某些数组元素丢失或多余,则此测试将失败

如果某些散列不包括指定的键-值对,则此测试将失败

如果数组元素顺序错误,则此测试将失败

Ruby相关问答推荐

安全导航运算符的使用是否应该在两种情况下进行单元测试(对象存在 + 对象无)?

这是一个很好的测试?规范

RSpec 模拟对象示例

Ruby检测方法

哈希或其他对象的内存大小?

ruby中字符的整数值?

退出(exit)和中止(abort)有什么区别?

Ruby 对象打印为指针

用mustache迭代数组

为什么 Ruby 使用 respond_to?而不是 responds_to?

如何将 STDOUT 捕获到字符串?

如何在 ruby​​ 中针对正则表达式测试整个字符串?

使用 for each 时识别最后一个循环

用 Ruby 解析 XML

如何通过反射获得活动记录关联

如何在不等式中使用Ruby case ... when?

了解 ruby​​-prof 输出

从Ruby中的子类方法调用父类中的方法

为什么表达式 (true == true == true) 会产生语法错误?

Ruby:如何在不指向同一个对象的情况下复制变量?