Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby's Test::Unit::TestCase, how do I override the initialize method?

I'm struggling with Test::Unit. When I think of unit tests, I think of one simple test per file. But in Ruby's framework, I must instead write:

class MyTest < Test::Unit::TestCase     def setup     end     def test_1     end     def test_1     end end 

But setup and teardown run for every invocation of a test_* method. This is exactly what I don't want. Rather, I want a setup method that runs just once for the whole class. But I can't seem to write my own initialize() without breaking TestCase's initialize.

Is that possible? Or am I making this hopelessly complicated?

like image 531
someguy Avatar asked Nov 01 '08 19:11

someguy


People also ask

What are test cases in Ruby?

Structuring and Organizing Tests Tests for a particular unit of code are grouped together into a test case, which is a subclass of Test::Unit::TestCase. Assertions are gathered in tests, member functions for the test case whose names start with test_.


2 Answers

As mentioned in Hal Fulton's book "The Ruby Way". He overrides the self.suite method of Test::Unit which allows the test cases in a class to run as a suite.

def self.suite     mysuite = super     def mysuite.run(*args)       MyTest.startup()       super       MyTest.shutdown()     end     mysuite end 

Here is an example:

class MyTest < Test::Unit::TestCase     class << self         def startup             puts 'runs only once at start'         end         def shutdown             puts 'runs only once at end'         end         def suite             mysuite = super             def mysuite.run(*args)               MyTest.startup()               super               MyTest.shutdown()             end             mysuite         end     end      def setup         puts 'runs before each test'     end     def teardown         puts 'runs after each test'     end      def test_stuff         assert(true)     end end 
like image 119
Matt Wolfe Avatar answered Oct 04 '22 23:10

Matt Wolfe


FINALLY, test-unit has this implemented! Woot! If you are using v 2.5.2 or later, you can just use this:

Test::Unit.at_start do   # initialization stuff here end 

This will run once when you start your tests off. There are also callbacks which run at the beginning of each test case (startup), in addition to the ones that run before every test (setup).

http://test-unit.rubyforge.org/test-unit/en/Test/Unit.html#at_start-class_method

like image 40
jpgeek Avatar answered Oct 05 '22 00:10

jpgeek