7.2. Ruby's Test::UnitRuby uses a testing framework known as Test::Unit (sometimes referred to as test/unit ) to run your application's tests. Test::Unit is similar to the xUnit frameworks that you find in other programming languages, and implements four major concepts:
Suppose you have the following non-Rails class: class BasicNumber def initialize( number ) @value = number end def add( x ) @value + x end def multiply( x ) @value * x end end Here is an example of a set of tests for this class: require "basic_number.rb" require "test/unit" class TestBasicNumber < Test::Unit::TestCase def test_basic_add num = BasicNumber.new(16) assert_equal(20, num.add(4) ) assert_equal(0, num.add(-16) ) # this test will fail, to show what happens on failure assert_equal(100, num.add(99), "Adding 99 doesn't work") end def test_basic_multiply num = BasicNumber.new(16) assert_equal(32, num.multiply(2) ) assert_equal(8, num.multiply(0.5) ) end end When you run this test file, it produces this output: >ruby test_basic_number.rb Loaded suite test_basic_number Started F. Finished in 0.015 seconds. 1) Failure: test_basic_add(TestBasicNumber) [test_basic_number.rb:11]: Adding 99 doesn't work. <100> expected but was <115>. 2 tests, 5 assertions, 1 failures, 0 errors When you run the test class, it automatically runs all the tests. You don't need to explicitly call a test runner or create a test suite. Just subclassing Test::Unit::TestCase and running the file causes the tests to be executed. Test::Unit provides a large number of assertions you can use, and Table 7-1 shows the main ones. Most assert methods take an optional message parameter. If a message is included, then that message is displayed if its assertion fails. Table 7-1. Commonly used assertions
You can define two special methods in your test case class: setup and teardown . Just before each test method is executed, setup is called to allow you to set up the environment for the test ( open a database connection, load test data, and so on). Likewise, immediately after each test method returns, teardown is called to clean up and release any resources acquired by setup . |