Heads up: RSpec-Mocks' #stub_const will define intermediate modules that have not been loaded yet

Posted . Visible to the public. Repeats.

The issue: You are using stub_const to change a constant value for your test.

stub_const "SomeClass::CONST", 'test'

All of a sudden, tests fail with undefined method 'some_method' for #<SomeClass:0x00000000101433a8>.

The reason

When using stub_const before the Class containing the constant has been loaded, a module is automatically created with the name.

Since RSpec does no autoloading, it will create a SomeClass module by itself. This is arguably a good idea.

As a workaround, use stub_const in your Rails specs like this:

stub_const "#{SomeClass}::CONST", 'test'

This will invoke Rails' autoloading and fix RSpec's behavior for you.

Dominik Schöler
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2017-12-13 15:13)