Star Development Corporation

"Every man and every woman is a star" -- Liber AL vel Legis 1.3

Chapter 1: The Basics - Part 2

Test-Driven Development

From here, we'll add a test. Notice that we have modified the method hello to give a return value that will make sense in the test. The return value from a puts in this situation is nil, which doesn't help in testing the code. The lesson here is to write the tests first, which we will do in future lessons.

HelloTest.rb

#!/usr/bin/env ruby -w
require 'test/unit'

class Greetings
  def hello(name)
    a = 'Hello, ' + name + '!'
    puts a
    return a
  end
end

g = Greetings.new
g.hello('world')

class TestHello < Test::Unit::TestCase
  def test_hello
    name = 'world'
    assert_equal("Hello, world!", Greetings.new.hello(name))
  end
end
Now, enter ./HelloTest.rb (Omit the ./ and, optionionally, the .rb if running on a Windows machine)
The results are (your Finished in may vary):
=> Hello, world!
=> .
=> Finished in 0.015 seconds.
=>
=> 1 tests, 1 assertions, 0 failures, 0 errors
Success!

Refactoring

What we need to do next is refactor the code into the main program and a test program

hello-main.rb

#!/usr/bin/env ruby -w

class Greetings
  def hello(name)
    'Hello, ' + name + '!'
  end
end

def main
  g = Greetings.new
  puts g.hello('world')
end

main
hello-test-02.rb
#!/usr/bin/env ruby -w
require 'test/unit'
require 'hello-main'

class TestHello < Test::Unit::TestCase
  def test_hello
    name = 'world'
    assert_equal("Hello, world!", Greetings.new.hello(name))
  end
end
Enter ./hello-main rb Results are:
Hello, world!

Now, enter ./hello-test-02.rb The results are (your Finished in may vary):
Started
.
Finished in 0.0 seconds.

1 tests, 1 assertions, 0 failures, 0 errors
And now each program does exactly what it is supposed to do. On to Chapter 2.
[Contents] [Back] [Next]
[Home] [Links]