如何匹配包含忽略数组元素顺序的数组的哈希?

Evg*_*nii 6 ruby rspec2

我有两个包含数组的哈希。就我而言,数组元素的顺序并不重要。有没有一种简单的方法可以在 RSpec2 中匹配此类哈希?

{ a: [1, 2] }.should == { a: [2, 1] } # how to make it pass?
Run Code Online (Sandbox Code Playgroud)

聚苯乙烯

有一个数组匹配器,它忽略顺序。

[1, 2].should =~ [2, 1] # Is there a similar matcher for hashes?
Run Code Online (Sandbox Code Playgroud)

解决方案

该解决方案对我有用。最初由 tokland 建议,已修复。

RSpec::Matchers.define :match_hash do |expected|
  match do |actual|
    matches_hash?(expected, actual) 
  end
end

def matches_hash?(expected, actual) 
  matches_array?(expected.keys, actual.keys) &&
    actual.all? { |k, xs| matches_array?(expected[k], xs) }
end   

def matches_array?(expected, actual)
  return expected == actual unless expected.is_a?(Array) && actual.is_a?(Array)
  RSpec::Matchers::BuiltIn::MatchArray.new(expected).matches? actual
end
Run Code Online (Sandbox Code Playgroud)

使用匹配器:

{a: [1, 2]}.should match_hash({a: [2, 1]})
Run Code Online (Sandbox Code Playgroud)

tok*_*and 2

我会写一个自定义匹配器:

RSpec::Matchers.define :have_equal_sets_as_values do |expected|
  match do |actual|
    same_elements?(actual.keys, expected.keys) && 
      actual.all? { |k, xs| same_elements?(xs, expected[k]) }
  end

  def same_elements?(xs, ys)
    RSpec::Matchers::BuiltIn::MatchArray.new(xs).matches?(ys)
  end
end

describe "some test" do
  it { {a: [1, 2]}.should have_equal_sets_as_values({a: [2, 1]}) }  
end

# 1 example, 0 failures
Run Code Online (Sandbox Code Playgroud)