【发布时间】:2012-02-03 23:46:16
【问题描述】:
我正在创建一些具有多种输入的测试。我正在测试一个包含新用户和回访用户类型、不同产品、促销代码、支付选项的采购网站。我觉得这是一个数据驱动的测试集,可能需要 csv 或电子表格格式的测试输入。
我一直在使用 rspec,它非常适合我创建的最后一个测试集。
我希望获得一致的结果格式。我被困在如何将数据表与 RSpec 一起使用。有人使用 RSpec 和测试输入表吗?
提前感谢您提供直接的解决方案或合理的建议。
【问题讨论】:
我正在创建一些具有多种输入的测试。我正在测试一个包含新用户和回访用户类型、不同产品、促销代码、支付选项的采购网站。我觉得这是一个数据驱动的测试集,可能需要 csv 或电子表格格式的测试输入。
我一直在使用 rspec,它非常适合我创建的最后一个测试集。
我希望获得一致的结果格式。我被困在如何将数据表与 RSpec 一起使用。有人使用 RSpec 和测试输入表吗?
提前感谢您提供直接的解决方案或合理的建议。
【问题讨论】:
如果您要使用表格,我会在测试文件中内联定义它,例如...
[
%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
【讨论】:
一种惯用的方法是使用带有参数的 RSpec shared examples。我将假设每个表行对应一个不同的测试用例,并且列分解了所涉及的变量。
例如,假设您有一些代码可以根据汽车的配置计算其价格。假设我们有一个 Car 类,我们想测试 price 方法是否符合制造商的建议零售价 (MSRP)。
我们可能需要测试以下组合:
门 |颜色 |内饰 |建议零售价 -------------------------------- 4 |蓝色 |布 | $X 2 |红色 |皮革 | $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
当我们运行这个规范时,输出应该是这样的:
车 #价钱 它的行为应该像 msrp 当 4 门, 蓝色, 布 应该等于 X 当 2 门, 红色, 皮革 应该等于 Y【讨论】:
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
【讨论】: