Indigo
Indigo

Reputation: 2997

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.

Upvotes: 0

Views: 455

Answers (2)

Indigo
Indigo

Reputation: 2997

Thanks to @Stefan's suggestion above, this is what worked for me.

# Modules Abc and Pqr also do not exist yet
let(:class_name) { 'Abc::Pqr::SomeMagic' }
let(:fake_class) { Class.new { def do_some_magic; end } }
let(:magic_class) { class_double(stub_const(class_name, fake_class)).as_stubbed_const }
let(:magic_class_instance) { instance_double(magic_class) }

before do
  allow(magic_class).to(receive(:new).and_return(magic_class_instance))
  allow(magic_class_instance).to(receive(:do_some_magic).and_return('some value'))
end

Upvotes: 0

Stefan
Stefan

Reputation: 114138

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.

Upvotes: 2

Related Questions