Rspec:如何正确测试模板方法模式?

时间:2015-06-26 13:58:05

标签: ruby rspec template-method-pattern

给定两个使用模板方法设计模式的类:

def Parent
  def all_params
    params.merge(extra_params)
  end

  def params
    {blah: "cool"}
  end

  def extra_params
    {}
  end
end

def Child < Parent
  def extra_params
    {edmund: "coolest"}
  end
end

在Rspec中测试此功能的正确方法是什么?我应该像这样创建shared_examples_for "a parent",然后在两个类中使用it_should_behave_like 'a parent'进行测试吗?:

shared_examples_for "a parent" do
  describe "#params" do
    expect(subject.params).to eq (...)
  end

  describe "#all_params" do
    expected_params = subject.all_params.merge(subject.extra_params)
    expect(subject.all_params).to eq expected_params
  end
end

describe Parent do
  subject { Parent.new }
  it_should_behave_like 'a parent'

  describe "#extra_params" do
    expect(subject.extra_params).to eq {}
  end
end

describe Child do
  subject { Child.new }
  it_should_behave_like 'a parent'

  describe "#extra_params" do
    expect(subject.extra_params).to eq {edmund: 'coolest'}
  end
end

或者我应该测试Child是否为父,并且只测试它覆盖的钩子方法?

describe Parent do
  subject { Parent.new }
  describe "#params" do
    expect(subject.params).to eq (...)
  end

  describe "#all_params" do
    expected_params = subject.all_params.merge(subject.extra_params)
    expect(subject.all_params).to eq expected_params
  end

  describe "#extra_params" do
    expect(subject.extra_params).to eq {}
  end
end

describe Child do
  subject { Child.new }
  it "is a Parent" do
    expect(subject).to_be kind_of(Parent)
  end

  describe "#extra_params" do
    expect(subject.extra_params).to eq {edmund: 'coolest'}
  end
end

2 个答案:

答案 0 :(得分:0)

这是一个选择问题。我个人为父类创建共享示例,然后为父类创建例如include_examples 'Animal'

Badger < Animal

并且例如it_behaves_like 'Animal'

behaves like Animal

第一个包含当前上下文的示例,而第二个包含示例在{{1}}上下文中。

答案 1 :(得分:0)

我更喜欢第二个例子。在it_behaves_like "a parent"中使用Child是重复的,基本上只是测试继承是否在Ruby中工作。