简体   繁体   English

用RSpec测试哈希数组的最佳方法是什么?

[英]What is the best way to test array of hashes with RSpec?

I'm trying to test array of hashes with RSpec, but I don't know how to test them because the hash order could change. 我正在尝试使用RSpec测试哈希数组,但是我不知道如何测试哈希数组,因为哈希顺序可能会改变。 EG: 例如:

[{name: 'John', age: 40, country: {abrev: 'US', name: 'United States'}}, {name: 'Peter', age: 43, country: {abrev: 'US', name: 'United States'}}]

is the same as: 是相同的:

[{name: 'Peter', age: 43, country: {abrev: 'US', name: 'United States'}}, {name: 'John', age: 40, country: {abrev: 'US', name: 'United States'}}]

What is the best way to test them using RSpec? 使用RSpec对其进行测试的最佳方法是什么? Should I use a custom matcher? 我应该使用自定义匹配器吗?

You could use RSpec's contain_exactly matcher, that doesn't care about ordering. 您可以使用RSpec的contains_exactly匹配器,该匹配器不关心排序。

expect(collection).to contain_exactly(
  {name: 'John', age: 40, country: {abrev: 'US', name: 'United States'}},
  {name: 'Peter', age: 43, country: {abrev: 'US', name: 'United States'}}
)

Another option is to use match_array , which behaves similarly (order is not important), but the expected argument is an array, rather than individual elements. 另一个选择是使用match_array ,其行为类似(顺序并不重要),但是期望的参数是数组,而不是单个元素。

expect(collection).to match_array([
  {name: 'John', age: 40, country: {abrev: 'US', name: 'United States'}},
  {name: 'Peter', age: 43, country: {abrev: 'US', name: 'United States'}}
])

To test for array equality without order you could use: 要不按顺序测试数组是否相等,可以使用:

expect(foo).to match_array(bar)

Or: 要么:

foo.should =~ bar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM