2011-07-09 22 views

回答

3

通常的測試應該在孤立地;如果你的很多測試需要做同樣的事情,那表明他們正在複製一些工作。但有時這是不可避免的 - 例如,您經常需要一個登錄用戶方便地測試已認證的事物。

特別是在Ruby測試的情況下,很可能有人已經寫了一個庫來解決你想要的特定問題。例如,在正常測試操作之前需要一些數據是很常見的 - 這就是爲什麼存在factory_girl

如果您想要執行行爲驅動的集成測試,並逐步完成用戶實際執行的所有步驟,則應該使用Cucumber

如果你想重用在不同地方的方法,你可以把共享代碼spec/support

# spec/support/consumable_helper.rb 
module ConsumableHelper 
    def consume(consumable) 
    calories = consumable.om_nom_nom 
    end 
end 

RSpec.configure do |config| 
    config.include ConsumableHelper 
end 

如果你想測試在多個領域相同的行爲,使用shared_examples_forit_behaves_like

shared_examples_for "a Consumable" do 
    it "should be delicious" do 
    subject.should be_delicious 
    end 

    it "should provide nutrition" do 
    subject.calories.should > 0 
    end 
end 

describe Fruit do 
    it_behaves_like "a Consumable" 
end 

describe Meat do 
    it_behaves_like "a Consumable" 
end 
+0

Right,+1,doc here:http://rspec.info/documentation/ – apneadiving

+0

不相關的附註。我更喜歡使用一個不定的文章......'shared_examples_for「一個消費品」'和'it_behaves_like「一個消費品」'。我只是發現DSL讀取更好:) – d11wtq