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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)