Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec: What are the alternatives to 'allow_any_instance_of'?

In the documentation the Rspec Mocks maintainers

... discourage its use for a number of reasons...

The reasons listed seem to relate to the expect version of this functionality, but they make no distinction between the two.

I can see why the expect version is discouraged, but the allow version doesn't seem to share the problems listed.

It seems like using the allow version is the most expedient way to test certain types of behaviour.

Example:

I'm testing authorization of some routes. One approach is to fabricate a user in the DB, but that seems fairly heavy handed, I prefer to just create a mock object and return it during the authorize call. This example is a specific case of testing code that uses complex libraries, which are tested separately.

Given that it's discouraged, what are the better alternatives?

like image 452
agbodike Avatar asked Nov 21 '22 17:11

agbodike


1 Answers

Per the documentation that you posted, the reason to not use allow_any_instance_of is that it is too heavy handed and can cover up potential code smells that you might miss. With that said, I still use it... they definitely aren't offering up an alternative, so if you need that functionality and have pondered other options or other ways to write your tests and decided against those, just use it.

like image 101
jmkoni Avatar answered Dec 30 '22 06:12

jmkoni