隐藏已定义常量
使用 hide_const
在测试期间删除常量。
隐藏顶级常量
假设一个名为“hideconstspec.rb”的文件,其中包含
FOO = 7
RSpec.describe "hiding FOO" do
it "can hide FOO" do
hide_const("FOO")
expect { FOO }.to raise_error(NameError)
end
it "restores the hidden constant when the example completes" do
expect(FOO).to eq(7)
end
end
当我运行 rspec hide_const_spec.rb
那么示例应该全部通过。
隐藏嵌套常量
假设一个名为“hideconstspec.rb”的文件,其中包含
module MyGem
class SomeClass
FOO = 7
end
end
module MyGem
RSpec.describe SomeClass do
it "hides the nested constant when it is fully qualified" do
hide_const("MyGem::SomeClass::FOO")
expect { SomeClass::FOO }.to raise_error(NameError)
end
it "restores the hidden constant when the example completes" do
expect(MyGem::SomeClass::FOO).to eq(7)
end
end
end
当我运行 rspec hide_const_spec.rb
那么示例应该全部通过。
隐藏未定义常量
假设一个名为“hideconstspec.rb”的文件,其中包含
RSpec.describe "hiding UNDEFINED_CONSTANT" do
it "has no effect" do
hide_const("UNDEFINED_CONSTANT")
expect { UNDEFINED_CONSTANT }.to raise_error(NameError)
end
it "is still undefined after the example completes" do
expect { UNDEFINED_CONSTANT }.to raise_error(NameError)
end
end
当我运行 rspec hide_const_spec.rb
那么示例应该全部通过。