17.7. Writing Unit Tests by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

17.7. Writing Unit Tests

Credit: Steve Arneil

Problem

You want to write some unit tests for your software, to guarantee its correctness now and in the future.

Solution

Use Test::Unit, the Ruby unit testing framework, from the Ruby standard library.

Consider a simple class for storing the name of a person. The Person class shown below stores a first name, a last name, and an age: a person's full name is available as a computed value. This code might go into a Ruby script called app/person.rb:

	# app/person.rb
	class Person
	  attr_accessor :first_name, :last_name, :age

	  def initialize(first_name, last_name, age)
	    raise ArgumentError, "Invalid age: #{age}" unless age > 0
	    @first_name, @last_name, @age = first_name, last_name, age
	  end

	  def full_name
	    first_name + ' ' + last_name
	  end
	end

Now, let's write some unit tests for this class. By convention, these would go into the file test/person_test.rb.

First, require the Person class itself and the Test::Unit framework:

	# test/person_test.rb
	require File.join(File.dirname(__FILE__), '..', 'app', 'person')
	require 'test/unit'

Next, extend the framework class Test::Unit::TestCase with a class to contain the actual tests. Each test should be written as a method of the test class, and each test method should begin with the prefix test. Each test should make one or more assertions: statements about the code which must be true for the code to be correct. Below are three test methods, each making one assertion:

 class PersonTest < Test::Unit::TestCase def test_first_name ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required