Given a ruby script with a bunch of functions, how can you unit test the functions in the script without running the script itself? Here is an example script, and here is its unit test.
给定一个带有许多函数的ruby脚本,如何在不运行脚本本身的情况下对脚本中的函数进行单元测试呢?这是一个示例脚本,这是它的单元测试。
For example, using require or load in my unit test causes the script to execute before the tests execute. I have many of these scripts and I really prefer they remain unaltered.
例如,在我的单元测试中使用require或load使脚本在测试执行之前执行。我有很多这样的剧本,我真的希望它们保持不变。
I guess I could load the file as a string, chop it up in memory and run eval - if viable, this feels like a terrible solution.
我想我可以以字符串的形式加载文件,在内存中分割它并运行eval——如果可行的话,这看起来是一个糟糕的解决方案。
Any thoughts or suggested strategies would be greatly appreciated.
如有任何想法或建议,我们将不胜感激。
2 个解决方案
#1
8
Usually you put the last lines actually running the script inside a guard like this:
通常你会把最后几行实际运行的脚本放在这样的一个保护中:
if $0 == __FILE__
# do stuff
end
i.e. if the first argument is this file, then it is being run as a script, and "stuff" will be executed; otherwise only the method definitions will be loaded.
例如,如果第一个参数是这个文件,那么它将作为脚本运行,并且“stuff”将被执行;否则将只加载方法定义。
#2
1
What I like to do is limit the executable part to be nothing more than the instantiation of an object, or even just a single class method call (possibly passing the cmd line args). Then write an class or series of class methods that will be invoked by the script, but can be tested separately and individually.
我喜欢做的是将可执行部分限定为对象的实例化,甚至是一个类方法调用(可能通过cmd行args)。然后编写一个类或一系列类方法,这些方法将由脚本调用,但可以单独测试。
This makes it easy to TDD and easier to reuse elsewhere.
这使得TDD变得容易,在其他地方更容易重用。
#1
8
Usually you put the last lines actually running the script inside a guard like this:
通常你会把最后几行实际运行的脚本放在这样的一个保护中:
if $0 == __FILE__
# do stuff
end
i.e. if the first argument is this file, then it is being run as a script, and "stuff" will be executed; otherwise only the method definitions will be loaded.
例如,如果第一个参数是这个文件,那么它将作为脚本运行,并且“stuff”将被执行;否则将只加载方法定义。
#2
1
What I like to do is limit the executable part to be nothing more than the instantiation of an object, or even just a single class method call (possibly passing the cmd line args). Then write an class or series of class methods that will be invoked by the script, but can be tested separately and individually.
我喜欢做的是将可执行部分限定为对象的实例化,甚至是一个类方法调用(可能通过cmd行args)。然后编写一个类或一系列类方法,这些方法将由脚本调用,但可以单独测试。
This makes it easy to TDD and easier to reuse elsewhere.
这使得TDD变得容易,在其他地方更容易重用。