模拟未定义常量

使用 stub_const 模拟常量。当常量未定义时,所有必要的中间模块将被动态创建。当示例完成后,中间模块常量将被移除,将常量状态恢复到初始状态。

模拟顶层常量

假设一个名为“stubconstspec.rb”的文件,其中包含

RSpec.describe "stubbing FOO" do
  it "can stub undefined constant FOO" do
    stub_const("FOO", 5)
    expect(FOO).to eq(5)
  end

  it "undefines the constant when the example completes" do
    expect { FOO }.to raise_error(NameError)
  end
end

我运行 rspec stub_const_spec.rb

那么所有示例都应该通过。

模拟嵌套常量

假设一个名为“stubconstspec.rb”的文件,其中包含

module MyGem
  class SomeClass
  end
end

module MyGem
  RSpec.describe SomeClass do
    it "can stub an arbitrarily deep constant that is undefined" do
      expect(defined?(SomeClass::A)).to be_falsey
      stub_const("MyGem::SomeClass::A::B::C", 3)
      expect(SomeClass::A::B::C).to eq(3)
      expect(SomeClass::A).to be_a(Module)
    end

    it 'undefines the intermediary constants that were dynamically created' do
      expect(defined?(SomeClass)).to be_truthy
      expect(defined?(SomeClass::A)).to be_falsey
    end
  end
end

我运行 rspec stub_const_spec.rb

那么所有示例都应该通过。