[RSpec] stub_const で定数の stub(スタブ)化

Thu, February 21, 2013 - 1 min read

RSpec で、定数を stub(スタブ)化するには stub_const メソッドを使います。

(例)定数 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

(例)Class や 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

[参考]:Stub Defined Constant - Stubbing constants - RSpec Mocks - RSpec - Relish はてなブックマーク - Stub Defined Constant - Stubbing constants - RSpec Mocks - RSpec - Relish