生成许多几乎相同的 ruby 单元测试
我有许多 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 并自动创建 LetterATest
、LetterBTest
等吗?如果是这样,您将如何去做以及为什么?
I have a number of ruby files (a.rb
, b.rb
, c.rb
) which define very similar classes. (They should test the same)
I've written a unit test to test these subclasses and I've generated contexts for each of the classes programatically (see below) — should I instead programatically create entire Test Classes instead? If so why and how?
I'm using the shoulda
unit test extensions so my files look something like this:
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
This does the job reasonably well, but should I do some other jiggerypokery and create LetterATest
, LetterBTest
etc. automatically instead? If so, how would you go about doing it and why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这实际上取决于您的类的相似程度,但假设它们几乎相同并且需要一些小测试,并且您正在使用 Shoulda,您可以执行以下操作:
在我们的代码库中,我们发现大量自动生成的上下文和测试会导致测试执行速度相当慢,因此我们倾向于使用上述方法来最大限度地减少上下文/测试的数量。你可能没有这个问题。
This really depends on how similar your classes are, but assuming they're pretty much identical and require a few small tests, and you're using shoulda, you could do something like:
In our codebase we've found that a large number of auto-generated contexts and tests leads to pretty slow test execution, so we favor the approach above to minimize the number of contexts/tests. You may not have this issue.