Intro to Ruby - Testing

Ruby

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

Tags:

Sunday, March 8th, 2009 Software

No comments yet.

Leave a comment

You must be logged in to post a comment.