【问题标题】:How to repeat a test case without duplicate code?如何在没有重复代码的情况下重复测试用例?
【发布时间】:2010-03-04 23:35:16
【问题描述】:

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

谢谢,

布莱恩

【问题讨论】:

    标签: ruby-on-rails unit-testing shoulda


    【解决方案1】:

    您可以为当前示例尝试类似的方法

    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
    

    【讨论】:

    • 太棒了!这正是我想要的。谢谢!
    猜你喜欢
    • 2018-12-31
    • 2012-03-21
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多