1

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

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
4

2 回答 2

0

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

include_examples 'Animal'

对于例如Badger < Animal

it_behaves_like 'Animal'

第一个将示例包含到当前上下文中,而第二个将示例包装在behaves like Animal上下文中。

于 2015-06-26T14:09:33.820 回答
0

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

于 2015-06-26T18:08:13.607 回答