Tuesday, June 21, 2011

Testing Ruby Scripts Without .rb Extension

Say you you want to test functions in a ruby script that doesn't have a ".rb" extension. Below are 2 tips.

To start writing you test you must use 'load' and NOT 'require.' Require is to load libraries (.so, .dll, etc) and will search for a file with a .rb extension. Load on the other hand loads ruby scripts and does not require a .rb extension. You will actually get an error if you use require saying "can't find file blah_blah"

Matz does a better job explaining the differences between the two:

"require is to load "libraries", where load is to load "scripts". The
target of the load method might be configuration files, or anything
else from the specified path, but at least they are all Ruby scripts.
On the other hand, the require method loads Ruby libraries or dynamic
loading C implemented libraries reside in the load path. So it needs
file path extension to distinguish which kind of library to read."

The above was taken from here.

Once the load fires your script will be executed immediately! To stop that from happening wrap the entry point of your ruby script with "if $0 == __FILE__…end" This says, if the current file (__FILE__) is equal to the running program ($0) then execute this block. This still allows you to execute the script with a direct call.

EOL