Search code examples
ruby-on-railsrubyrspecrspec-railsrspec3

Stub class instance inside module that doesn't exist


For a spec, I am trying to stub a new class (MyClass) inside a new module (NewModule) both of which do not exist yet.

This spec is for the class which utilizes MyClass

let(:my_class) { instance_double('ParentModule::NewModule::MyClass', extract_values: expected_value) }

ParentModule: already exist

NewModule: Doesn't yet exist

MyClass: Doesn't yet exist

Unfortunately, it throws this error

NameError:
       uninitialized constant ParentModule::NewModule

Any suggestions what would be the correct way to achieve this.


Solution

  • You can stub a constant via stub_const:

    let(:my_class) { stub_const('ParentModule::NewModule::MyClass', Class.new) }
    

    From the docs:

    When the constant is not already defined, all the necessary intermediary modules will be dynamically created. When the example completes, the intermediary module constants will be removed to return the constant state to how it started.