Writing Unit Tests
require 'test/unit'
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
class PersonTest < Test::Unit::TestCase
def test_first_name
person = Person.new('J', 'Y', 25)
assert_equal 'J', person.first_name
end
def test_last_name
person = Person.new('J', 'Y', 25)
assert_equal 'Y', person.last_name
end
def test_full_name
person = Person.new('J', 'Y', 25)
assert_equal 'J Y', person.full_name
end
def test_age
person = Person.new('J', 'Y', 25)
assert_equal 25, person.age
assert_raise(ArgumentError) { Person.new('J', 'Y', -4) }
assert_raise(ArgumentError) { Person.new('J', 'Y', 'four') }
end
end
# $ ruby test/person_test.rb
Related examples in the same category