空对象替身
测试替身 默认情况下是严格的,当它们接收到未被允许或预期的消息时会引发错误。你可以在 double
上链式调用 as_null_object
来使替身变为“宽松”。对于任何未明确允许或预期的消息,替身都会返回自身。它充当黑洞空对象,允许任意深度的消息链。
as_null_object
允许任意深度的消息链,并返回自身
假设有一个名为“as_null_object_spec.rb”的文件,其中包含
RSpec.describe "as_null_object" do
it "returns itself" do
dbl = double("Some Collaborator").as_null_object
expect(dbl.foo.bar.bazz).to be(dbl)
end
end
当我运行 rspec as_null_object_spec.rb
那么示例都应该通过。
个别方法仍然可以被允许或预期
假设有一个名为“as_null_object_spec.rb”的文件,其中包含
RSpec.describe "as_null_object" do
it "can allow individual methods" do
dbl = double("Some Collaborator", :foo => 3).as_null_object
allow(dbl).to receive(:bar).and_return(4)
expect(dbl.foo).to eq(3)
expect(dbl.bar).to eq(4)
end
end
当我运行 rspec as_null_object_spec.rb
那么示例都应该通过。