Ruby’s Test::Unit

Ruby 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, like JUnit for Java or NUnit for .NET. Any testing framework uses the same fundamental flow. With any test case, you do the following:

  • Set up the preconditions for the test. Rails will give you some help here by setting up a database with fixtures that have sample data you define.

  • Use your application. You’ll write code to exercise your application.

  • Compare the result to what you expected to happen. You will use assertions to make these comparisons.

To say it another way, testing is about stimulus and response. You stimulate your code and observe the response, over and over. If the response is what you expect, the test passes. Otherwise, the test fails. Here’s a simple test for a few arithmetic operations in Ruby:

require 'test/unit'

class NumberTest < Test::Unit::TestCase
  
  def test_should_add_two_numbers
    result = 4 + 4            # Use the code
    assert_equal 8, result    # Measure your results against your expectations
  end
  
  def test_should_divide_two_numbers
    result = 11 / 2           # Use the code
    assert_equal 5.5, result  # Measure your results against your expectations
  end
  
end

In this case, the code being tested is the base Ruby libraries for two math operators, division and addition. Each test exercises some code and then makes an assertion about the expected result. An assertion is ...

Get Rails: Up and Running, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.