Intro to Ruby - Testing

Overview
The following is a demonstration of testing in Ruby using the Test::Unit framework that is provided with Ruby by default. Other testing frameworks worth considering are:
- RSpec - My testing framework of choice at the moment. Focuses on behavior driven design (BDD).
- Shoulda - Another testing framework that integrates nicely with Test::Unit and even plays well with RSpec in some cases.
Test::Unit will be more familiar to those from the Java space due to the assert methods. A good gem to use for automation of your testing is the ZenTest (a.k.a. autotest) gem.
Code
# Requirements for Test::Unit
require "test/unit"
# A simple class to be used for testing.
class Simple
def self.who_am_i
"I am #{name.downcase}"
end
def add a, b
a + b if a && b
end
def multiply a, b
a * b if a && b
end
def echo string = "Echo"
string
end
end
# The test class that captures the various tests to be run against the Simple class.
class SimpleTest < Test::Unit::TestCase
def setup
@simple = Simple.new
end
def test_good_add
assert @simple.add(1, 1), 2
end
def test_bad_add
assert_nil @simple.add(nil, nil)
end
def test_who_am_i
assert_kind_of String, Simple.who_am_i
end
end
Output
Started
...
Finished in 0.000347 seconds.
3 tests, 3 assertions, 0 failures, 0 errors
Download
The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 14-testing.rb.
What’s Next
Article Series - Intro to Ruby
- Intro to Ruby - Getting Started
- Intro to Ruby - Strings
- Intro to Ruby - Numbers
- Intro to Ruby - Ranges
- Intro to Ruby - Arrays
- Intro to Ruby - Hashes
- Intro to Ruby - Variables and Scopes
- Intro to Ruby - Methods
- Intro to Ruby - Blocks
- Intro to Ruby - Classes
- Intro to Ruby - Modules
- Intro to Ruby - Conditionals
- Intro to Ruby - Loops
- Intro to Ruby - Exceptions
- Intro to Ruby - Testing
- Intro to Ruby - Next Steps
No comments yet.
Leave a comment
You must be logged in to post a comment.
Search
Categories
- Adventures
(105)
- Announcements
(36)
- Business
(19)
- Electronics
(28)
- Employment
(1)
- Epicurean
(10)
- Games
(3)
- Literature
(1)
- Mechanical
(4)
- Meetups
(18)
- Movies
(2)
- Music
(26)
- Photography
(1)
- Services
(29)
- Software
(136)