结构与红宝石测试双倍 [英] Struct vs test double in ruby

查看:55
本文介绍了结构与红宝石测试双倍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在结构上使用rspec double的利弊是什么?例如

What would the pros and cons be of using an rspec double over a struct? For example

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)

vs.

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 >

vs.

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 >

vs.

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!

这是几个例子-我确信还有更多的理由偏爱测试双打.

That's a few examples -- I'm sure there are more reasons to prefer test doubles.

这篇关于结构与红宝石测试双倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆