结构与测试在ruby中加倍

在结构上使用rspec double有什么优缺点? 例如

before :each do location = double "locatoin" location.stub(:id => 1) end 

VS

 before :each do location = Struct.new("locatoin", :id) location.new.id = 1 end 

测试双打更容易设置

 Slip = Struct.new(:id) slip = Slip.new(:id => 1) 

 slip = double('slip', :id => 1) 

测试双精度生成更多信息性错误消息

 require 'spec_helper' class TooLongError < StandardError; end class Boat def moor(slip) slip.moor!(self) rescue TooLongError false end end describe Boat do let(:boat) { subject } context "when slip won't accept boat" do it "can't be moored" do Slip = Struct.new('Slip') slip = Slip.new boat.moor(slip).should be_false end end end 
 Failure/Error: slip.moor!(self) NoMethodError: undefined method `moor!' for # 

 it "can't be moored" do slip = double('slip') boat.moor(slip).should be_false end 
 Failure/Error: slip.moor!(self) Double "slip" received unexpected message :moor! with (#) 

测试双打有更好的测试支持

 class Boat def moor(slip) slip.dont_care slip.moor!(self) rescue TooLongError false end end it "can't be moored" do Slip = Struct.new('Slip') slip = Slip.new slip.should_receive(:moor!).and_raise(TooLongError) boat.moor(slip).should be_false end 
 Failure/Error: slip.dont_care NoMethodError: undefined method `dont_care' for # 

 it "can't be moored" do slip = double('slip').as_null_object slip.should_receive(:moor!).and_raise(TooLongError) boat.moor(slip).should be_false end 

0 failures # passed!

这是一些例子 - 我确信有更多理由更喜欢测试双打。