json_spec
json_spec copied to clipboard
Allow matching out-of-order arrays with .in_any_order
My team needed a way to reliably, consistently test the JSON returned by our API, despite the facts that:
- the controller that builds the JSON might retrieve models in any order (not deterministic), and
- the client that will consume the JSON does not care about the order of models in the array.
For example, our API might respond with {"objects":[{"id":1,"some_attribute":"foo"},{"id":2,"some_attribute":"bar"}]} and that would be totally valid, but it is just as likely to respond with {"objects":[{"id":2,"some_attribute":"bar"},{"id":1,"some_attribute":"foo"}]} instead, and that should also be valid.
To allow the be_json_eql matcher to match out-of-order arrays, I've added the chain method .in_any_order. It works by sorting each array in lexical order according to the JSON string representation of the element.
You can also pass false to .in_any_order if you want to, which then behaves as if you had not chained .in_any_order at all (in case someone needs to determine indifference dynamically at runtime).
Examples are available in the modified be_json_eql_spec.rb file. I also added some tests to ensure that this feature should work correctly when combined with the other features of this matcher.
Our team also need this functionality. :+1: to be merged
@aliismayilov It looks like the project managers haven't touched this repository in a few months... so, if you like, you can just use my fork for now!
thanks @rusterholz !!
Bump!
I incorporated your feedback from above in my latest commit.
This would be very useful
Is there an alternative for this functionality or plans to merge it?
Stumbled on this today, what a fine vintage this PR is. Would be useful to us as well.
Also stumbling across this just now. This would be very useful functionality.
+1 from me too