ruby – Rails / RSpec:如何测试#initialize方法?

前端之家收集整理的这篇文章主要介绍了ruby – Rails / RSpec:如何测试#initialize方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何使用RSpec指定#initialize行为?例如:

generator.rb

class Generator
  attr_accessor :seed

  def initialize(seed = nil)
    @seed = seed || pick_seed
  end

  def pick_seed
    Time.now.to_i
  end
end

generator_spec.rb

require 'generator'

describe Generator

  it "calls 'pick_seed' method unless seed specified" do
  end

end

我想设置期望从#initialize方法调用的pick_seed方法.

解决方法

对我来说,期望是在协作者之间设计对话.所以,你必须决定 – #pick_seed是内部实现细节还是协作角色界面的一部分?

如果pick_seed是一个实现细节,期望是工作的错误工具.而且,因为你有一个种子的访问器,你可以这样进行(注意一个例子)

class Generator
  attr_accessor :seed

  def initialize(seed = nil)
    @seed = seed || pick_seed
  end

  def pick_seed
    Time.now.to_i
  end
end

describe Generator do
  context "creating" do 
    context "when a seed is specified" do
      it "uses that seed" do
        seed = 123
        generator = Generator.new(seed)
        generator.seed.should == seed
      end
    end
    context "when a seed is not specified" do
      it "creates its own seed" do
        generator = Generator.new
        generator.seed.should_not be_nil
      end
    end
  end
end

OTOH,如果选择种子是“种子选择器”角色的一部分,那么嘲讽在设计种子选择器时是有价值的,依赖注入是分配角色的标准方法.你可以写下如下:

class GeneratorWithCollaborator
  attr_accessor :seed

  def initialize(seed = nil,seed_picker = self)
    @seed = seed || seed_picker.pick_seed
  end

  def pick_seed
    Time.now.to_i
  end
end

describe GeneratorWithCollaborator do
  context "creating" do
    context "when a seed is specified" do
      it "uses that seed" do
        seed = 123
        seed_picker = double('seed picker')
        seed_picker.should_not_receive(:pick_seed)
        generator = GeneratorWithCollaborator.new(seed,seed_picker)
        generator.pick_seed
      end
    end

    context "when a seed is not specified" do
      it "delegates to its seed picker" do
        seed_picker = double('seed picker')
        seed_picker.should_receive(:pick_seed)
        generator = GeneratorWithCollaborator.new(nil,seed_picker)
      end
    end
  end
end
原文链接:https://www.f2er.com/ruby/272086.html

猜你在找的Ruby相关文章