如何在rspec中测试哈希顺序等价:should_receive .with matchers?

时间:2014-08-20 13:58:17

标签: ruby rspec

Ruby已经订购了哈希,但在测试等效时没有测试排序。通过排序测试哈希等价的常用方法是hash1.to_a == hash2.to_a。但是,在rspec should_receive .with matchers中,你似乎坚持测试常规等价。有一些解决方法,比如向MyClass添加另一个方法,它提供了存储在ordered_hash中的内容并测试了它的.to_a,但是我想知道是否有更清洁或更惯用的方法来测试有序等效的哈希与rspec should_receive .with。

class MyClass
  def self.ordering
    [:v_1, :v_2]
  end

  def self.foo(unordered_hash)
    ordered_hash = unordered_hash.sort_by{|key, _| ordering.index(key)}.to_h
    bar(ordered_hash)
  end

  def self.bar(ordered_hash)
  end
end

unordered_hash = {v_2: 2, v_1: 1}
# would succeed even though it actually received {v_1: 1, v_2: 2}
MyClass.should_receive(:bar).with({v_2: 2, v_1: 1})
MyClass.foo(unordered_hash)

1 个答案:

答案 0 :(得分:0)

据我记得should_receive接受块来测试更复杂的参数测试,例如:

MyClass.should_receive(:bar) { |ordered_hash|
  ordered_hash.to_a.should == {v_2: 2, v_1: 1}.to_a
}