如何在ruby模块中包含unit testing?

我正在尝试将模块的unit testing包含在与模块本身相同的源文件中,遵循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 

现在,我可以运行执行此源文件的unit testing。

但是 ,当我需要/从另一个脚本加载它们时,它们也会运行。 如何避免这种情况?

有没有更惯用的方法来实现这一点,除非这种做法不鼓励?

就个人而言,我从来没有听说有人试图在Ruby中这样做。 这绝对不是一种标准做法。 那说你可以利用这个技巧:

 if __FILE__ == $0 # Do something.. run tests, call a method, etc. We're direct. end 

if块中的代码仅在文件直接执行时执行,而不是在另一个库或应用程序需要时执行。

更多ruby技巧: http : //www.rubyinside.com/21-ruby-tricks-902.html

它在Ruby中实际上并不常见,尽管它肯定不是Rails中的常见做法。

您可能遇到的一个问题与本文相同,即模块确实应该包含在类中以便测试它们。 通过将模块包含在您的测试用例中来测试模块当然是可能的,但是您正在测试模块是否在混合到Test :: Unit :: TestCase时工作,而不是当它混合到更有用的东西时它会工作。

因此,unit testing应该存在于类文件中,或者如果您只是想要一般可用的方法,则使用类函数而不是模块。

您可以使用minitest在模块源代码本身中包含unit testing。

试试这个例子:

 class Foo < String end if $0 == __FILE__ require 'minitest/autorun' require 'minitest/pride' class FooTest < MiniTest::Unit::TestCase def test_foo_instantiation foo = Foo.new() assert_instance_of Foo, foo end def test_foo_parent_class foo = Foo.new() assert_kind_of String, foo end end end 

在这里,我创建了一个名为Foo的类,它inheritance自String类。 然后我创建了两个unit testing。 在第一个测试中,我检查我是否可以实例化Foo类的对象。 在第二个测试中,我检查类Foo的实例化对象是一种String。

如果此代码写在名为foo.rb的文件中,我可以使用以下命令运行测试:

 ruby foo.rb 

Minitest执行起来很快。 “骄傲”模块允许您以彩色字体输出测试结果,这在眼睛上很好。

刚发现一种方法可以防止在脚本需要模块时执行unit testing。 unit.rb中有一个标志位于.../lib/ruby/1.8/test/中设置为true。

结合samg技巧(再次感谢),我们可以写:

 if (__FILE__ != $0) Test::Unit.run = true ### do not run the unit tests end 
Interesting Posts