如何在Ruby模块中包含单元测试? [英] How to include unit tests in a ruby module?
问题描述
我试图在 Perl modulino 模型.
#! /usr/bin/env ruby
require 'test/unit'
module Modulino
def modulino_function
return 0
end
end
class ModulinoTest < Test::Unit::TestCase
include Modulino
def test_modulino_function
assert_equal(0, modulino_function)
end
end
现在,我可以运行执行此源文件的单元测试.
Now, I can run the unit-tests executing this source file.
但是,当我需要/从另一个脚本加载它们时,它们也会运行.如何避免这种情况?
But, they are also run when I require/load them from another script. How can this be avoided ?
除非不鼓励这种做法,否则使用Ruby是否有更惯用的方式来实现这一目标?
Is there a more idiomatic way to achieve this with Ruby, unless this practice is discouraged ?
推荐答案
我个人从来没有听说过有人试图在Ruby中这样做.这绝对不是标准做法.也就是说,您也许可以利用此技巧:
Personally I've never heard of anyone trying to do this in Ruby. It's definitely not a standard practice. That said you may be able to leverage this trick:
if __FILE__ == $0
# Do something.. run tests, call a method, etc. We're direct.
end
if
块中的代码仅在直接执行文件时执行,而不是在其他库或应用程序需要时执行.
The code in the if
block will only execute if the file is executed directly, not if it's required by another library or application.
此处提供更多红宝石技巧: http://www.rubyinside.com/21 -ruby-tricks-902.html
More ruby tricks here: http://www.rubyinside.com/21-ruby-tricks-902.html
这篇关于如何在Ruby模块中包含单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!