使用 unstub
unstub
删除一个方法存根,本质上是提前清理方法存根,而不是等待在示例结束时运行的清理。较新的非猴子补丁语法没有直接等效项,但在大多数情况下,可以使用 and_call_original
来实现相同的行为。区别在于 obj.unstub(:foo)
完全清理 foo
方法存根,而 allow(obj).to receive(:foo).and_call_original
继续观察对方法的调用(在使用 间谍 时很重要),这可能会影响方法的行为,如果它对 caller
进行了任何操作,因为它将包含额外的 rspec 堆栈帧。
背景
假设一个名为“spec/spec_helper.rb”的文件,其中包含
RSpec.configure do |config|
config.mock_with :rspec do |mocks|
mocks.syntax = :should
end
end
以及一个名为“.rspec”的文件,其中包含
--require spec_helper
取消存根一个方法
假设一个名为“spec/unstub_spec.rb”的文件,其中包含
RSpec.describe "Unstubbing a method" do
it "restores the original behavior" do
string = "hello world"
string.stub(:reverse) { "hello dlrow" }
expect {
string.unstub(:reverse)
}.to change { string.reverse }.from("hello dlrow").to("dlrow olleh")
end
end
当我运行 rspec spec/unstub_spec.rb
那么示例应该全部通过。