开发者

How to repeat a test case without duplicate code?

开发者 https://www.devze.com 2022-12-21 19:58 出处:网络
I\'m using shoulda with Ruby on Rails, and I have the following test cases: class BirdTest < Test::Unit::TestCase

I'm using shoulda with Ruby on Rails, and I have the following test cases:

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

It works well but I hate the duplicate code I've written here. So I'm hoping to write a test case like the following. This test case should be run several times, and each time the value of some_bird is set to a different one. Is that doable?

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

Thanks,

Bryan


You could try something like this for your current example

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

精彩评论

暂无评论...
验证码 换一张
取 消