Read more

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

Dominik Schöler
December 13, 2017Software engineer at makandra GmbH

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

stub_const "SomeClass::CONST", 'test'
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Dominik Schöler to makandra dev (2017-12-13 16:13)