by http://webgeektutorials.blogspot.com

Thursday, June 16, 2011

Ruby: Unit Testing


Unit Testing is a great way to catch errors early in the development process, if you dedicate time to writing appropriate and useful tests. As in other languages, Ruby provides a framework in its standard library for setting up, organizing, and running tests called Test::Unit.
There are other very popular testing frameworks, rspec and cucumber come to mind.
Specifically, Test::Unit provides three basic functionalities:
  1. A way to define basic pass/fail tests.
  2. A way to gather like tests together and run them as a group.
  3. Tools for running single tests or whole groups of tests.
Writing a UNIT TEST 
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

No comments:

Post a Comment