Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include unit tests in a ruby module?

I'm trying to include the unit tests for a module in the same source file as the module itself, following the Perl modulino model.

#! /usr/bin/env ruby

require 'test/unit'

module Modulino
    def modulino_function
        return 0
    end
end

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

Now, I can run the unit-tests executing this source file.

But, they are also run when I require/load them from another script. How can this be avoided ?

Is there a more idiomatic way to achieve this with Ruby, unless this practice is discouraged ?

like image 661
philant Avatar asked Dec 01 '09 16:12

philant


People also ask

How do I run a test case in Ruby?

We can run all of our tests at once by using the bin/rails test command. Or we can run a single test file by passing the bin/rails test command the filename containing the test cases. This will run all test methods from the test case.

Can modules include other modules Ruby?

Indeed, a module can be included in another module or class by using the include , prepend and extend keywords. Before to start this section, feel free to read my article about the Ruby Object Model if you're unfamiliar with the ancestor chain in Ruby.

How do you access a module method in Ruby?

To access the instance method defined inside the module, the user has to include the module inside a class and then use the class instance to access that method.


2 Answers

Personally I've never heard of anyone trying to do this in Ruby. It's definitely not a standard practice. That said you may be able to leverage this trick:

if __FILE__ == $0
  # Do something.. run tests, call a method, etc. We're direct.
end

The code in the if block will only execute if the file is executed directly, not if it's required by another library or application.

More ruby tricks here: http://www.rubyinside.com/21-ruby-tricks-902.html

like image 154
samg Avatar answered Sep 21 '22 12:09

samg


It's actually not that uncommon in Ruby though it's certainly not the common practice in Rails.

One of the issues you may be running into is the same as this post which is that modules really should be included in classes in order to test them. It's certainly possible to test a module by including it in your test case but you're testing whether the module works when mixed into Test::Unit::TestCase, not that it'll work when you mix it into something more useful.

So unit tests should probably live on the class file or if you just want generally available methods use a class function instead of a module.

like image 41
Chuck Vose Avatar answered Sep 18 '22 12:09

Chuck Vose