2012-01-06 15 views
8

我正在創建一些具有各種輸入的測試。我正在測試採購網站,其中包含新的和返回的用戶類型,不同的產品,促銷代碼,付款方式。我覺得這是一個數據驅動的測試集,可能需要測試輸入的csv或電子表格格式。組織RSpec中具有因子組合的測試的最佳方法

我一直在使用rspec,這對於我創建的最後一個測試集是完美的。

我想要有一致的結果格式。我被困在如何使用RSpec的數據表。有沒有人使用RSpec和一張測試輸入表?

預先感謝您提供直接解決方案或合理建議。

回答

14

如果你打算使用一個表,我會在線測試文件類似中定義它...

[ 
    %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 
+0

這幾乎是我所期待的,只是我會做的「它「應該做的表無論「做」部分。謝謝! – 2012-01-06 08:01:09

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 
2

一慣用方法是使用帶參數的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 
相關問題