views:

42

answers:

2

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 many 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.

+2  A: 

usually you put the last lines actually running the script inside a guard like this:

if __FILE__ == $0
  #do stuff 
end

i.e if the first argument is this file it is being run as a script, otherwise don't do stuff just load the definitions.

ormuriauga
Good suggestion, although I was trying to avoid adding these lines to the script/s for presentation purposes - I am using the scripts as a learning aid (AI not ruby).
jasonb
+1  A: 

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.

olore