开发者

How to unit test functions in a ruby script without running the script

开发者 https://www.devze.com 2023-01-19 19:22 出处:网络
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.

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.

For example, using require or load in my unit test causes the script to execute before the tests execute. I have man开发者_Go百科y of these scripts and I really prefer they remain unaltered.

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.

Any thoughts or suggested strategies would be greatly appreciated.


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.


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.

This makes it easy to TDD and easier to reuse elsewhere.

0

精彩评论

暂无评论...
验证码 换一张
取 消