1

我有许多定义非常相似的类的 ruby​​ 文件 ( a.rb, b.rb, )。c.rb(他们应该测试相同)

我已经编写了一个单元测试来测试这些子类,并且我已经以编程方式为每个类生成了上下文(见下文)——我应该改为以编程方式创建整个测试类吗?如果是这样,为什么以及如何?

我正在使用shoulda单元测试扩展,所以我的文件看起来像这样:

a.rb

class ItsA
  def number
    1123
  end
end

b.rb

class ItsB
  def number
    6784
  end
end

test_letters.rb

require 'rubygems'
require 'test/unit'
require 'shoulda'

class LettersTest < Test::Unit::TestCase
  Dir.glob('letters/*.rb') do |letter|
    context "The #{letter} letter file"
      setup do
        # Here I require the ruby file and allocate
        # @theclass to be an instance of the class in the file.
        # I'm actually testing JavaScript using Harmony, but 
        # putting those details in might complicate my question.
      end

      should "return a number" do
        assert @theclass.number.is_a? Number
      end
    end
  end

这可以很好地完成这项工作,但是我应该自动做一些其他的 jiggerypokery 和 createLetterATestLetterBTest吗?如果是这样,你会怎么做,为什么?

4

1 回答 1

1

这实际上取决于您的类的相似程度,但假设它们几乎相同并且需要一些小测试,并且您使用的是 shoulda,您可以执行以下操作:

class LettersTest < Test::Unit::TestCase
  context "The letter classes"
    setup do
      @instances = # your code to get a list of the instances
    end

    should "return a number" do
      @instances.each do |instance|
        assert instance.number.is_a?(Number), "#{instance.class}.number should be a number"
      end
    end
  end
end

在我们的代码库中,我们发现大量自动生成的上下文和测试会导致测试执行速度非常慢,因此我们倾向于使用上述方法来最小化上下文/测试的数量。你可能没有这个问题。

于 2010-08-24T21:39:31.153 回答