Stub class 模块内不存在的实例

Stub class instance inside module that doesn't exist

对于规范,我正在尝试在新模块 (NewModule) 中添加一个新的 class (MyClass),这两个模块尚不存在。

此规范适用于使用 MyClass

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

父模块:已经存在

新模块:尚不存在

MyClass:尚不存在

不幸的是,它抛出了这个错误

NameError:
       uninitialized constant ParentModule::NewModule

任何建议是什么是实现此目标的正确方法。

您可以通过 stub_const:

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

来自文档:

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.

感谢上面@Stefan 的建议,这对我有用。

# 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