2010-03-04 178 views
2

我使用的是用Ruby早該on Rails的,我有以下測試案例:如何重複沒有重複代碼的測試用例?

class BirdTest < Test::Unit::TestCase 

    context "An eagle" do 
     setup do 
     @eagle = Eagle.new 
     end 
     should "be able to fly" do 
     assert_true @eagle.can_fly? 
     end 
    end 

    context "A Crane" do 
     setup do 
     @crane = Crane.new 
     end 
     should "be able to fly" do 
     assert_true @crane.can_fly? 
     end 
    end 

    context "A Sparrow" do 
     setup do 
     @sparrow = Sparrow.new 
     end 
     should "be able to fly" do 
     assert_true @sparrow.can_fly? 
     end 
    end 

end 

它運作良好,我只是不喜歡重複的代碼,我在這裏寫的。所以我希望寫下如下的測試用例。這個測試用例應該運行幾次,並且每次將some_bird的值設置爲不同的值。這是可行的嗎?

class BirdTest < Test::Unit::TestCase 

    context "Birds" do 
     setup do 
     @flying_bird = some_bird 
     end 
     should "be able to fly" do 
     assert_true @flying_bird.can_fly? 
     end 
    end 

end 

感謝,

布萊恩

回答

2

你可以嘗試這樣的事情你當前的例子

class BirdTest < Test::Unit::TestCase 
    context "Birds" do 
    [Crane, Sparrow, Eagle].each do |bird| 
     context "A #{bird.name}" do 
     should "be able to fly" do 
      this_bird = bird.new 
      assert this_bird.can_fly? 
     end 
     end 
    end 
    end 
end 
+0

太棒了!這正是我想要的。謝謝! – Shuo 2010-03-05 07:36:31