json_spec icon indicating copy to clipboard operation
json_spec copied to clipboard

Allow matching out-of-order arrays with .in_any_order

Open rusterholz opened this issue 11 years ago • 9 comments
trafficstars

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.

rusterholz avatar Oct 24 '14 02:10 rusterholz

Our team also need this functionality. :+1: to be merged

aliismayilov avatar Jan 16 '15 14:01 aliismayilov

@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!

rusterholz avatar Jan 20 '15 14:01 rusterholz

thanks @rusterholz !!

aliismayilov avatar Jan 26 '15 10:01 aliismayilov

Bump!

I incorporated your feedback from above in my latest commit.

rusterholz avatar Jun 24 '15 19:06 rusterholz

This would be very useful

opsb avatar Oct 08 '15 11:10 opsb

Is there an alternative for this functionality or plans to merge it?

madis avatar Dec 18 '18 17:12 madis

Stumbled on this today, what a fine vintage this PR is. Would be useful to us as well.

askreet avatar Aug 03 '20 12:08 askreet

Also stumbling across this just now. This would be very useful functionality.

jfo84 avatar Aug 04 '20 07:08 jfo84

+1 from me too

jji-fieldwire avatar Mar 30 '21 22:03 jji-fieldwire