RSpec: comparing a hash with string keys against a hash with symbol keys?

fearless_fool picture fearless_fool · Aug 6, 2012 · Viewed 14.1k times · Source

Consider the following RSpec snippet:

it "should match" do
  {:a => 1, :b => 2}.should =~ {"a" => 1, "b" => 2}
end

This test fails because one hash uses symbols for keys and the other uses strings for keys. In my case, one hash is a parsed JSON object, the other is the hash that created the object. I'd like them to compare as equal.

Before I go writing my own matcher or coercing both hashes to have string keys, is there a matcher or technique that handles this (common) case?

Answer

Shailen Tuli picture Shailen Tuli · Aug 6, 2012

You could do:

it "should match" do
    {:a => 1, :b => 2}.stringify_keys.should =~ {"a" => 1, "b" => 2}
end