简体   繁体   English

比较哈希数组与红宝石中的正则表达式

[英]Comparing array of hashes with regex in ruby

I have two array of hashes. 我有两个哈希表。 Actual array is one I'm getting through my test and I have expected array stored somewhere in files with which I compare the actual one. 实际数组是我正在通过测试的数组,我期望将数组存储在文件中的某个位置,以便与实际数组进行比较。

  • Actual array 实际数组

    [ {:var1=>nil, :action=>"open", :Run=>"App", :Id=>"A123-B456-C789"}, {:var1=>nil, :Id=>"P987-Q654-R321"} ]

  • Expected array 预期数组

    [ {:var1=>nil, :action=>"open", :Run=>"App", :Id=>"A123-B456-C789"}, {:var1=>nil, :Id=>"P987-Q654-R321"} ]

Currently, I am using Rspec::Matcher match_array to compare and it is working perfectly: 当前,我正在使用Rspec :: Matcher match_array进行比较,并且运行良好:

expect(actual).to match_array(expected)

Problem : 问题

Id in actual array in every hash is dynamic. 每个哈希中的实际数组中的id是动态的。 So, I can not compare it with expected value. 因此,我无法将其与期望值进行比较。 Here, I would like compare if it is not nil or check pattern with some regex. 在这里,我想比较一下是否为nil或使用某些正则表达式检查模式。 Something like this: 像这样:

{:var1=>nil, :Id=> !nil or /some-regex/}

Not sure if it's doable with Rspec Matcher or I need to change matcher library? 不知道它是否可以与Rspec Matcher一起使用,还是我需要更改Matcher库?

Thanks in advance! 提前致谢!

Use a double: 使用双:

let(:id_double) { double('id') }
let(:expected) do
  [
    { var1: nil, action: 'open', Run: 'App', Id: id_double },
    { var1: nil, Id: id_double }
  ]
end

before do
  allow(id_double).to receive(:==) do |other_id|
    other_id =~ /^[A-Z]\d{3}-[A-Z]\d{3}-[A-Z]\d{3}$/
  end
end

it 'works' do
  actual = # ...
  expect(actual).to match_array(expected)
end

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

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