简体   繁体   English

在Module / Class的末尾执行代码,比如Ruby test / unit

[英]Execute code at end of Module/Class, like Ruby test/unit

Ruby's unit testing framework executes unit tests even though nobody creates unit test object. Ruby的单元测试框架执行单元测试,即使没有人创建单元测试对象。 For example, 例如,

in MyUnitTest.rb 在MyUnitTest.rb中

require 'test/unit'

class MyUnitTest < Test::Unit::TestCase
    def test_true
        assert true
    end
end

and when i invoke that script as 当我调用该脚本时

ruby MyUnitTest.rb

test_true method gets executed automatically. test_true方法自动执行。 How is this done? 这是怎么做到的?

I am trying to come up with a framework that can do similarly. 我试图提出一个可以做类似的框架。 I dont want "if __ FILE __ == $0" at the end of every module that uses my framework. 我不想在使用我的框架的每个模块的末尾“if __ FILE __ == $ 0”。

thanks. 谢谢。

Test::Unit uses at_exit for this, which runs code immediately before your application quits: Test::Unit使用at_exit ,在应用程序退出之前立即运行代码:

at_exit do
  puts "printed before quit"
end

.. other stuff

I don't think there is any way to run code specifically after a class or module definition is closed. 在关闭类或模块定义之后,我认为没有任何方法可以专门运行代码。

Similar to Daniel Lucraft's answer , you could define a finalizer guard to have some code run when the garbage collector runs: Daniel Lucraft的答案类似,您可以定义一个终结器防护,以便在垃圾收集器运行时运行一些代码:

ObjectSpace.define_finalizer(MyClass, lambda {
  puts "printed before MyClass is removed from the Object space"
})

But personally I think at_exit is a better fit since its timing is a bit more deterministic. 但我个人认为at_exit更合适,因为它的时机更具确定性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM