测试替身
测试替身 是指在测试中代替真实对象的任何对象(想想“特技替身”)。你可以使用 `double` 方法创建一个。替身默认是“严格”的 - 任何你没有允许或预期的消息都会触发错误 - 但你可以切换替身变为“宽松”。创建替身时,你可以通过传递哈希来允许消息(并设置其返回值)。
我们建议你在可能的情况下使用验证替身。
替身默认是严格的
假设 一个名为“double_spec.rb”的文件,内容为
RSpec.describe "A test double" do
it "raises errors when messages not allowed or expected are received" do
dbl = double("Some Collaborator")
dbl.foo
end
end
当 我运行 `rspec double_spec.rb`
那么 它应该失败,并显示
#<Double "Some Collaborator"> received unexpected message :foo with (no args)
哈希可用于定义允许的消息和返回值
假设 一个名为“double_spec.rb”的文件,内容为
RSpec.describe "A test double" do
it "returns canned responses from the methods named in the provided hash" do
dbl = double("Some Collaborator", :foo => 3, :bar => 4)
expect(dbl.foo).to eq(3)
expect(dbl.bar).to eq(4)
end
end
当 我运行 `rspec double_spec.rb`
那么 这些示例应该全部通过。