模拟已定义常量
使用 stub_const
模拟常量。 当常量已定义时,模拟值将替换示例期间的原始值。
模拟顶级常量
假设一个名为“stub_const_spec.rb”的文件,其中包含
FOO = 7
RSpec.describe "stubbing FOO" do
it "can stub FOO with a different value" do
stub_const("FOO", 5)
expect(FOO).to eq(5)
end
it "restores the stubbed constant when the example completes" do
expect(FOO).to eq(7)
end
end
当我运行 rspec stub_const_spec.rb
时
那么示例应该全部通过。
模拟嵌套常量
假设一个名为“stub_const_spec.rb”的文件,其中包含
module MyGem
class SomeClass
FOO = 7
end
end
module MyGem
RSpec.describe SomeClass do
it "stubs the nested constant when it is fully qualified" do
stub_const("MyGem::SomeClass::FOO", 5)
expect(SomeClass::FOO).to eq(5)
end
end
end
当我运行 rspec stub_const_spec.rb
时
那么示例应该全部通过。
传输嵌套常量
假设一个名为“stub_const_spec.rb”的文件,其中包含
module MyGem
class SomeClass
FOO = 7
end
end
module MyGem
RSpec.describe SomeClass do
let(:fake_class) { Class.new }
it "does not transfer nested constants by default" do
stub_const("MyGem::SomeClass", fake_class)
expect { SomeClass::FOO }.to raise_error(NameError)
end
it "transfers nested constants when using :transfer_nested_constants => true" do
stub_const("MyGem::SomeClass", fake_class, :transfer_nested_constants => true)
expect(SomeClass::FOO).to eq(7)
end
it "can specify a list of nested constants to transfer" do
stub_const("MyGem::SomeClass", fake_class, :transfer_nested_constants => [:FOO])
expect(SomeClass::FOO).to eq(7)
end
end
end
当我运行 rspec stub_const_spec.rb
时
那么示例应该全部通过。