mnyon-grandkru / knowledgebase

An issue tracker of error messages discovered while developing as well as their solution.
https://github.com/mnyon-grandkru/knowledgebase/issues
MIT License
2 stars 0 forks source link

The message "method_name" was received by "object#instance1" but has already been received by "object#instance2" #50

Closed trystant closed 6 years ago

trystant commented 6 years ago

I'm receiving this error when working on a spec in Ruby and am running into a spec failure which seems to indicate that the message is being sent to the wrong user. It looks like the excpect_any_instance_of behavior isn't working as expected, according to this issue in https://github.com/rspec/rspec-mocks/issues/910.

Scanning this now, but it looks like the solution is to not use expect_any_instance_of in specs:

expect_any_instance_of does (and has always in our case) referred to a single instance, so the documentation is slightly wrong on this, (see #911), we consider the use of any_instance to be a code smell and only be useful when working with legacy code and so we don't really want to extend the behavior further.

Looking farther down the thread, it seems that some of the solutions include:

You have a few tactics here which are, in my opinion, better than using any instance.

Stub out the query chain and return a specific double. This is the best approach if you're attempting to test something outside of active record where you want the speed of using doubles over the reliability of an integration check. Assert on what you're passing the query and let active record do its magic in reality.

Don't stub this at all. If the query is sufficiently complex to require real execution then you shouldn't be stubbing the result, write it as an integration check.

Both. Refactor the query into a method on the model, or a on a service object and write an integration test checking the query, then use stub the method on a unit test for the object consuming the result of the query.

trystant commented 6 years ago

This was resolved by stubbing out the query as described earlier.