[RSpec] Stubbing Constants with stub_const

Tadashi Shigeoka ·  Thu, February 21, 2013

In RSpec, to stub constants, use the stub_const method.

(Example) Stubbing constant FOO

FOO = 7

describe "stubbing FOO" do
  it "can stub FOO with a different value" do
    stub_const("FOO", 5)
    FOO.should eq(5)
  end

  it "restores the stubbed constant when the example completes" do
    FOO.should eq(7)
  end
end

(Example) Stubbing constants in Class or Module

module MyGem
  class SomeClass
    FOO = 7
  end
end

module MyGem
  describe SomeClass do
    it "stubs the nested constant when it is fully qualified" do
      stub_const("MyGem::SomeClass::FOO", 5)
      SomeClass::FOO.should eq(5)
    end
  end
end

[Reference]:Stub Defined Constant - Stubbing constants - RSpec Mocks - RSpec - Relish

That’s all from the Gemba.