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

时间:2010-12-25 13:53:12

标签: ruby rspec2

如何使用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

我希望设置从pick_seed方法调用#initialize方法的期望。

1 个答案:

答案 0 :(得分:22)

对我来说,期望是关于设计合作者之间的对话。那么,您必须决定 - #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