如何使用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
方法的期望。
答案 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