freerange / mocha

A mocking and stubbing library for Ruby
https://mocha.jamesmead.org
Other
1.23k stars 158 forks source link

introduce #has_all parameter matcher #673

Open mohammednasser-32 opened 1 month ago

mohammednasser-32 commented 1 month ago

Recently I was trying to mock a method that receives an array of ids as an argument, I don't care about the order of the ids so I am not sorting when fetching the records. So the test was sometimes failing randomly as the order of the array is not consistent, example:

#test
my_service.stubs(:my_method).with([1,2])

#actual code on execution
my_service.my_method([2,1])

Using my_service.stubs(:my_method).with(includes(1, 2)) solved my issue...however the test will still pass if the array has an extra item which is not desirable in this case

my_service.my_method([3,2,1])

So I wanted to suggest introducing a has_all matcher that checks if two arrays contain the same elements regardless of their order.

If you think this would be useful, I would gladly open a PR for it

Thank you

floehopper commented 1 month ago

@mohammednasser-32

Thanks for your interest in Mocha. I am open to the idea of adding a matcher like this, but I'm not convinced about the name has_all, because an array that contains more than just the listed items could be described as "having all" the items. I think I'd want to include the word "exact" in the name somehow; maybe includes_exactly...?

As an aside, if we add a matcher like this, I'd like to add a similar one for hashes as per the note for this commit:

... I've added an optional exact keyword argument to the HasEntries constructor and set this to true when it's called from PositionalOrKeywordHash#matches?. I haven't bothered to document the new exact argument, because currently it's only used internally.

I can imagine introducing something like #has_exact_entries to the public API, but it would probably make sense to add something similar for exact matching of array items at the same time, so I'm going to leave that for now.

mohammednasser-32 commented 1 month ago

@floehopper perfect, I agree with includes_exactly..will work on it, and then I can work on has_exact_entries..thanks :pray:

mohammednasser-32 commented 1 month ago

@floehopper PR added