Rspec:正面和负面案例的干燥共享案例

时间:2014-04-03 14:13:47

标签: ruby unit-testing rspec

使用RSpec,如何编写一组DRY的shared_examples,可以用于正面和负面的情况?

适用于肯定案例的shared_examples示例:

shared_examples "group1" do
  it "can view a person's private info" do
    @ability.should be_able_to(:view_private_info, person)
  end
  # also imagine I have many other examples of positive cases here
end

如果有与it_should_behave_like相反的内容,例如it_should_not_behave_like,那就太棒了。我理解示例的文本必须是灵活的。

1 个答案:

答案 0 :(得分:0)

你可以这样做:

受测试的课程:

class Hat
  def goes_on_your_head?
    true
  end

  def is_good_to_eat?
    false
  end

end

class CreamPie
  def goes_on_your_head?
    false
  end

  def is_good_to_eat?
    true
  end

end

示例:

shared_examples "a hat or cream pie" do
  it "#{is_more_like_a_hat? ? "goes" : "doesn't go" } on your head" do
    expect(described_class.new.goes_on_your_head?).to eq(is_more_like_a_hat?)
  end

  it "#{is_more_like_a_hat? ? "isn't" : "is" } good to eat" do
    expect(described_class.new.is_good_to_eat?).to eq(!is_more_like_a_hat?)
  end

end

describe Hat do
  it_behaves_like "a hat or cream pie" do
    let(:is_more_like_a_hat?) { true }
  end
end

describe CreamPie do
  it_behaves_like "a hat or cream pie" do
    let(:is_more_like_a_hat?) { false }
  end
end

我不太可能在实际代码中执行此操作,因为编写可理解的示例描述会很困难。相反,我将制作两个共享示例并将重复提取到方法中:

def should_go_on_your_head(should_or_shouldnt)
  expect(described_class.new.goes_on_your_head?).to eq(should_or_shouldnt)
end

def should_be_good_to_eat(should_or_shouldnt)
  expect(described_class.new.is_good_to_eat?).to eq(should_or_shouldnt)
end

shared_examples "a hat" do
  it "goes on your head" do
    should_go_on_your_head true
  end

  it "isn't good to eat" do
    should_be_good_to_eat false
  end

end

shared_examples "a cream pie" do
  it "doesn't go on your head" do
    should_go_on_your_head false
  end

  it "is good to eat" do
    should_be_good_to_eat true
  end

end

describe Hat do
  it_behaves_like "a hat"
end

describe CreamPie do
  it_behaves_like "a cream pie"
end

当然,除非实际的例子足够复杂,否则我不会提取这些方法甚至使用共享的例子。