2

我将 shoulda 与 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

谢谢,

布莱恩

4

1 回答 1

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
于 2010-03-05T07:26:07.950 回答