-6ren">
gpt4 book ai didi

ruby - ruby 中的结构与测试双重

转载 作者:数据小太阳 更新时间:2023-10-29 06:58:31 26 4
gpt4 key购买 nike

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

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

对比

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 #<struct Struct::Slip >

对比

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 (#<Boat:0x106b90c60>)

测试替身对测试有更好的支持

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 #<struct Struct::Slip >

对比

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!

这只是几个例子——我相信还有更多理由更喜欢测试替身。

关于ruby - ruby 中的结构与测试双重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13848822/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com