我正在创建一些具有各种输入的测试。我正在测试采购网站,其中包含新的和返回的用户类型,不同的产品,促销代码,付款方式。我觉得这是一个数据驱动的测试集,可能需要测试输入的csv或电子表格格式。组织RSpec中具有因子组合的测试的最佳方法
我一直在使用rspec,这对于我创建的最后一个测试集是完美的。
我想要有一致的结果格式。我被困在如何使用RSpec的数据表。有没有人使用RSpec和一张测试输入表?
预先感谢您提供直接解决方案或合理建议。
我正在创建一些具有各种输入的测试。我正在测试采购网站,其中包含新的和返回的用户类型,不同的产品,促销代码,付款方式。我觉得这是一个数据驱动的测试集,可能需要测试输入的csv或电子表格格式。组织RSpec中具有因子组合的测试的最佳方法
我一直在使用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
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
一惯用方法是使用带参数的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
这几乎是我所期待的,只是我会做的“它“应该做的表无论“做”部分。谢谢! – 2012-01-06 08:01:09