Using RSpec, is there a way to compare two hashes where I don’t know what some values will be? I’ve tried using instance_of, but it doesn’t seem to work.
In my test, I am creating a new device object with a POST request and want to make sure I get the right JSON response back. It’s creating a UUID for the device (I’m not using a relational db), but I obviously won’t know what that value will be and don’t really care.
post "/projects/1/devices.json", name: 'New Device'
expected = {'name' => 'New Device', 'uuid' => instance_of(String), 'type' => 'Device'}
JSON.parse(body).should == expected
And I get the following error:
1) DevicesController API adds a new device to a project
Failure/Error: JSON.parse(body).should == expected
expected: {"name"=>"New Device", "uuid"=>#<RSpec::Mocks::ArgumentMatchers::InstanceOf:0x5a27147d @klass=String>, "type"=>"Device"}
got: {"name"=>"New Device", "uuid"=>"ef773465-7cec-48fd-b2a7-f1da10d1595a", "type"=>"Device"} (using ==)
Diff:
@@ -1,4 +1,4 @@
"name" => "New Device",
"type" => "Device",
-"uuid" => #<RSpec::Mocks::ArgumentMatchers::InstanceOf:0x5a27147d @klass=String>
+"uuid" => "ef773465-7cec-48fd-b2a7-f1da10d1595a"
# ./spec/api/devices_spec.rb:37:in `(root)'
instance_ofis for argument matching:Instead of using the
==operator you could useinclude. For example:which says that the key
uuidmust be present with any value andnameandtypeshould be present with the specified value. It will also allow other keys in the hash.I don’t know of a way to achieve exactly what you’re asking for with the built-in matchers.