注意未来的读者:认为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.