【问题标题】:RSpec match_array with hashes带有哈希的 RSpec match_array
【发布时间】:2021-11-11 16:26:45
【问题描述】:

我想知道是否有办法通过 RSpec 实现我想要的。所以我想测试一个看起来类似于这个的哈希数组:

array_example =
 [
  {
   id: 1, 
   link: "www.some-link.com/path_im_not_interested_in"
  }, 
  {
   id: 2, 
   link: "www.example-link.com/another_useless_path"
  }
 ]

我想做集成测试,我不会在链接中包含这些路径。我只对检查www.some-link.comwww.example-link.com 是否存在于数组中的这些哈希中感兴趣。像这样的:

expect(array_example).to match_array(
 [
  {
   id: 1, 
   link: "www.some-link.com"
  }, 
  {
   id: 2, 
   link: "www.example-link.com"
  }
 ]

但是这个显然行不通。有没有办法实现我想要的?我想避免使用自定义匹配器。

【问题讨论】:

  • 听起来你只想测试link:,即。你想忽略id:

标签: ruby rspec


【解决方案1】:

您可以使用组合匹配器:

expect(array_example)
  .to contain_exactly(
    a_hash_including(id: 1, link: a_string_including("www.some-link.com")),
    a_hash_including(id: 2, link: a_string_including("www.example-link.com"))
  )

更多信息请参见https://rspec.info/blog/2014/01/new-in-rspec-3-composable-matchers/

a_hash_including 的参数不必覆盖整个哈希,它只会检查你传递的键。

【讨论】:

  • 非常感谢,这正是我想要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-26
  • 2020-07-19
  • 2014-07-12
  • 2020-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多