fearless_fool fearless_fool - 2 months ago 14
Ruby Question

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

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

You could do:

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