fearless_fool fearless_fool - 2 years ago 142
Ruby Question

Is there an RSpec matcher for 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}

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 Source

You could do:

it "should match" do
    {:a => 1, :b => 2}.stringify_keys.should =~ {"a" => 1, "b" => 2}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download