在RSpec中组织具有因子组合的测试的最佳方法

时间:2012-01-06 07:12:19

标签: ruby csv rspec

我正在创建一些具有各种输入的测试。我正在测试一个购买网站,其中包含新的和返回的用户类型,不同的产品,促销代码,付款选项。我觉得这是一个数据驱动的测试集,可能需要测试输入的csv或电子表格格式。

我一直在使用rspec,这对我创建的最后一个测试集非常适合。

我希望获得一致的结果格式。我坚持如何使用RSpec数据表。有没有人使用RSpec和测试输入表?

提前感谢您提供直接解决方案或合理建议。

3 个答案:

答案 0 :(得分:16)

如果您打算使用表格,我会在测试文件中将其定义为类似......

[
  %w( abc  123  def  ),
  %w( wxyz 9876 ab   ),
  %w( mn   10   pqrs )
].each do |a,b,c|
  describe "Given inputs #{a} and #{b}" do
    it "returns #{c}" do
      Something.whatever(a,b).should == c
    end
  end
end

答案 1 :(得分:3)

一种惯用方法是将RSpec shared examples与参数一起使用。我将假设每个表行对应一个不同的测试用例,并且列分解了所涉及的变量。

例如,假设您有一些代码可以根据汽车的配置来计算汽车的价格。假设我们有一个班级Car,我们想测试price方法是否符合制造商的建议零售价(MSRP)。

我们可能需要测试以下组合:

Doors | Color | Interior | MSRP
--------------------------------
4     | Blue  | Cloth    | $X
2     | Red   | Leather  | $Y

让我们创建一个共享示例,捕获此信息并测试正确的行为。

RSpec.shared_examples "msrp" do |doors, color, interior, msrp|
  context "with #{doors} doors, #{color}, #{interior}" do
    subject { Car.new(doors, color, interior).price }
    it { should eq(msrp) }
  end
end

编写完这个共享示例后,我们可以简洁地测试多个配置,而不会产生代码重复的负担。

RSpec.describe Car do
  describe "#price" do
    it_should_behave_like "msrp", 4, "Blue", "Cloth", X
    it_should_behave_like "msrp", 2, "Red", "Leather", Y
  end
end

当我们运行此规范时,输出应采用以下形式:

Car
  #price
    it should behave like msrp
      when 4 doors, Blue, Cloth
        should equal X
      when 2 doors, Red, Leather
        should equal Y

答案 2 :(得分:2)

user_types = ['rich', 'poor']
products = ['apples', 'bananas']
promo_codes = [123, 234]
results = [12,23,34,45,56,67,78,89].to_enum
test_combis = user_types.product(products, promo_codes)

test_combis.each do |ut, p, pc|
  puts "testing #{ut}, #{p} and #{pc} should == #{results.next}"
end

输出:

testing rich, apples and 123 should == 12
testing rich, apples and 234 should == 23
testing rich, bananas and 123 should == 34
testing rich, bananas and 234 should == 45
testing poor, apples and 123 should == 56
testing poor, apples and 234 should == 67
testing poor, bananas and 123 should == 78
testing poor, bananas and 234 should == 89