微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby – 是否存在匹配哈希的RSpec2匹配器?

注意未来的读者:认为RSpec不认为你的哈希是相等的?一个可能是一个OrderedHash,但是从常规的RSpec输出你不能告诉.这是提示这个帖子的问题.

原来的问题:

假设我有一个规范,我想测试一个方法生成适当的哈希.

it 'should generate the Hash correctly' do
  expected = {:foo => 1,'baz' => 2}
  subject.some_method_that_should_generate_the_hash.should == expected
end

这通常会失败,因为具有相同键值对的不同哈希可能会以不同的顺序返回它们的对.结果如下:

Failure/Error: subject.some_method_that_should_generate_the_hash.should == expected
expected: {:foo => 1,'baz' => 2},got: {'baz' => 2,:foo => 1}

对于数组,这是使用=〜运算符来解决的.但是,这不适用于哈希.现在,我已经诉诸了

it 'should generate the Hash correctly' do
  expected = {:foo => 1,'baz' => 2}
  subject.some_method_that_should_generate_the_hash.each {|k,v|
    v.should == expected[k]
  }
end

但这似乎是不必要的冗长.我期望有一个明显的解决方案.我是在文档中忽略某些东西,还是RSpec没有适当的匹配器来实现无秩序哈希平等?

解决方法

describe 'Hash' do
  let(:x) { { :a => 1,:b => 2 } }
  let(:y) { { :b => 2,:a => 1 } }

  it "should be equal with ==" do
    x.should == y
  end
end

通行证.我不知道你的具体情况发生了什么.你有一些失败的例子,你可以分享

Ruby编程有这样的说法:

Equality — Two hashes are equal if they have the same default value,they contain the same number of keys,and the value corresponding to each key in the first hash is equal (using ==) to the value for the same key in the second.

原文地址:https://www.jb51.cc/ruby/272247.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐