Monday, February 4, 2008

Integrating Unit Tests In Ruby Scripts

When I write ruby scripts I like to use a single file, containing the program and all unit tests. It took me some time to find out how to add a command line switch to my ruby scripts that makes them run in script mode with full access to the Test::Unit command line arguments, while being able to run the script without the test framework interfering in the execution:


#!/usr/bin/ruby -w
require 'test/unit'

if ARGV.include?("--test")
ARGV.delete_at(ARGV.index("--test"))
else
Test::Unit::run = true
puts "Running..."
end


Now you can simply run the program by typing

$ ./testme.rb
Running...

or run the tests with

$ ./testme.rb --test
Loaded suite ./testme
Started

Finished in 0.0 seconds.

0 tests, 0 assertions, 0 failures, 0 errors

The nice thing is that only the first "--test" will be removed, so you can still leverage the Test::Unit command line argument interface.

2 comments:

  1. [...] way to tell a script that it should just execute it's unit tests and exit. See my blog post about integrating unit tests in Ruby scripts to learn how this can be done in Ruby. A very similar approach is possible for [...]

    ReplyDelete
  2. Business intelligence analyst
    SQIAR (http://www.sqiar.com/services/bi-strategy/) is a leading Business Intelligence company.Sqiar Provide business intelligence Services Which help the company to present Information in Meaningful form.

    ReplyDelete