For testing a JSON API response I recently had to compare two deeply nested structures.
To do this programmatically would be quite a pain, so I wrote a gem which tests a
prepared structure (imported JSON) against the output of my (unit test) code.
General
Use case: you’re writing an API response or a JSON export and want to unit test it.
Optionally you can ignore the leaf values or any hash key types/order (see below).
The gem gives error results with the path to where exactly the structures differ.
require'structure_compare'comparison=StructureCompare::StructureComparison.newexpected={a:1,b:2,c:[1,2,3]}actual={a:1,b:2,c:[1,2,"A"]}comparison.structures_are_equal?(expected,actual)putscomparison.error# => root[:c][2] : expected String to be kind of Fixnum
When dealing with floats, you will want to introduce a tolerance.
NOTE: Float::EPSILON is always used for comparing Float type values.
NOTE: The check_values option must be set.