Setup y Teardown

There are many cases where a small bit of code needs to be run before and/or after each test. Test/Unit provides the setup and teardown member functions, which are run before and after every test (member function).

[~/local/src/ruby/LPP/unit_testing/simple_example(master)]$ cat test/tc_simple_number3.rb 
# File:  tc_simple_number3.rb
 
require "simple_number"
require "test/unit"
 
class TestSimpleNumber < Test::Unit::TestCase
 
  def setup
    @num = SimpleNumber.new(2)
  end
 
  def teardown
    ## Nothing really
  end
 
  def test_simple
    assert_equal(4, @num.add(2) )
  end
 
  def test_simple2
    assert_equal(4, @num.multiply(2) )
  end
 
end

[~/local/src/ruby/LPP/unit_testing/simple_example(master)]$ cat Rakefile 
desc "Test class SimpleNumber"
task :test do
  sh "ruby -Ilib -Itest test/tc_simple_number.rb"
end

desc "Test with test/tc_simple_number2.rb. Expect failures"
task :test2 do
  sh "ruby -Ilib -Itest test/tc_simple_number2.rb"
end

desc "Test with test/tc_simple_number3.rb. setup adn teardown"
task :test3 do
  sh "ruby -Ilib -Itest test/tc_simple_number3.rb"
end

[~/local/src/ruby/LPP/unit_testing/simple_example(master)]$ rake test3
ruby -Ilib -Itest test/tc_simple_number3.rb
Run options: 

# Running tests:

..

Finished tests in 0.000988s, 2024.2915 tests/s, 2024.2915 assertions/s.

2 tests, 2 assertions, 0 failures, 0 errors, 0 skips



Casiano Rodriguez León 2015-06-18