スタブされた未定義の定数
stub_const を使用して定数をスタブします。定数がまだ定義されていない場合、必要な中間モジュールが動的に作成されます。例が完了すると、中間モジュールの定数は削除され、定数の状態が元の状態に戻ります。
トップレベルの定数をスタブする
次の内容のファイル "stub_const_spec.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 を実行すると、
すべての例がパスするはずです。
ネストされた定数をスタブする
次の内容のファイル "stub_const_spec.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 を実行すると、
すべての例がパスするはずです。