The job is done
Listen to this article.
In this blog I'm posting short summaries of "Programming Ruby"
Value: Average
Level: Normal
Summary:
You include Test::Unit facilities in your unit test with the "require 'test/unit'" line.
Unit tests seem to fall quite naturally into high-level groupings, called test cases, and
lower level groupings, the test methods themselves. Quite often you'll find all of the test methods within a test case setting up a particular scenario. Each test method then probes some aspect of that scenario. Finally, each method may then tidy up after itself. For example, we could be testing a class that extracts jukebox playlists from a database.
Memo: The classes that represent test cases must be subclasses of Test::Unit::TestCase.
Within a TestCase class, the setup and teardown methods bracket each test, rather than being run once per test case.
Example:
require 'test/unit'
require 'playlist_builder'
require 'dbi'
class TestPlaylistBuilder < Test::Unit::TestCase
def test_empty_playlist
db = DBI.connect('DBI:mysql:playlists')
pb = PlaylistBuilder.new(db)
assert_equal([], pb.playlist())
db.disconnect
end
def test_artist_playlist
db = DBI.connect('DBI:mysql:playlists')
pb = PlaylistBuilder.new(db)
pb.include_artist ("krauss")
assert(pb.playlist.size > 0, "Playlist shouldn't be empty")
pb.playlist.each do |entry|
assert_match(/krauss/i, entry.artist)
end
db.disconnect
end
def test_title_playlist
db = DBI.connect('DBI:mysql:playlists')
pb = PlaylistBuilder.new(db)
pb.include_title("midnight")
assert(pb.playlist.size > 0, "Playlist shouldn't be empty")
pb.playlist.each do |entry|
assert_match(/midnight/i, entry.title)
end
db.disconnect
end
# ...
end
Reported errata (at 10/17/06 14:17:18 PDT): 0
Errata I found: 0
My suggestions to the author: 0
Doubts: 0
You can test exceptions, too (see example code 2).
The final parameter to every assertion is a message, which is output before any
failure message. This normally isn't needed, as Test::Unit's messages are normally
pretty reasonable. The one exception is the test assert_not_nil, where the message
"<nil> expected to not be nil" doesn't help much. In that case, you may want to add
some annotation of your own (see example code 3).
Example:
require 'roman'
require 'test/unit'
class TestRoman < Test::Unit::TestCase
def test_range
assert_raise(RuntimeError) { Roman.new(0) }
assert_nothing_raised() { Roman.new(1) }
assert_nothing_raised() { Roman.new(499) }
assert_raise(RuntimeError) { Roman.new(5000) }
end
end
require 'test/unit'
class TestsWhichFail < Test::Unit::TestCase
def test_reading
assert_not_nil(ARGF.read, "Read next line of input")
end
end
produces:
Loaded suite -
Started
F
Finished in 0.033581 seconds.
1) Failure:
Read next line of input.
<nil> expected to not be nil.
1 tests, 1 assertions, 1 failures, 0 errors
test_reading(TestsWhichFail) [ prog.rb:4]: