2

私はRubyonRailsでshouldaを使用しており、次のテストケースがあります。

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 に答える