views:

28

answers:

1

This question is Ruby related.

Suppose I want to have the test unit for my class in the same file as it's definition. Is it possible to do so? For example, if I'd pass a "--test" argument when I run the file, I'd want it to run the test unit. Otherwise, execute normally.

Imagine a file like this:

require "test/unit"

class MyClass

end

class MyTestUnit < Test::Unit::TestCase
# test MyClass here
end

if $0 == __FILE__
   if ARGV.include?("--test")
      # run unit test
   else
      # run normally
   end
end

What code should I have in the #run unit test section?

+1  A: 

This can be achieved with a module:

#! /usr/bin/env ruby

module Modulino
    def modulino_function
        return 0
    end
end

if ARGV[0] == "-test"
    require 'test/unit'

    class ModulinoTest < Test::Unit::TestCase
        include Modulino
        def test_modulino_function
            assert_equal(0, modulino_function)
        end
    end
else
    puts "running"
end

or without module, actually:

#! /usr/bin/env ruby

def my_function
    return 0
end

if ARGV[0] == "-test"
    require 'test/unit'

    class MyTest < Test::Unit::TestCase
        def test_my_function
            assert_equal(0, my_function)
        end
    end
else
    puts "running rc=".my_function()
end
philippe