2005-11-18 19:00:39 +0900 (7293d); rev 54
勉強のため『テスト駆動開発入門』の「I. THE MONEY EXAMPLE.」のサンプルコードを Ruby で書いてみます。 少しずつ書き進めていく予定です。
このページの Diff を見ると初期のテストコードから少しずつ書き換えてゆく手順を確認できると思います。
class Money
attr_reader :amount
attr_accessor:currency
protected :amount
def initialize(amount, currency)
@amount = amount
@currency = currency
end
def self.dollar(amount)
Dollar.new(amount, :USD)
end
def self.franc(amount)
Franc.new(amount, :CHF)
end
def ==(other)
@amount == other.amount && self.class == other.class
end
end
class Dollar < Money
def times(multiplier)
Money.dollar(@amount * multiplier)
end
end
class Franc < Money
def times(multiplier)
Money.franc(@amount * multiplier)
end
end
if $0 == __FILE__
require 'test/unit'
class TestMoney < Test::Unit::TestCase
def test_multiplication
five = Money.dollar(5)
assert_equal(Money.dollar(10), five.times(2))
assert_equal(Money.dollar(15), five.times(3))
end
def test_franc_multiplication
five = Money.franc(5)
assert_equal(Money.franc(10), five.times(2))
assert_equal(Money.franc(15), five.times(3))
end
def test_equality
assert(Money.dollar(5) == Money.dollar(5))
assert(Money.dollar(5) != Money.dollar(6))
assert(Money.franc(5) == Money.franc(5))
assert(Money.franc(5) != Money.franc(6))
assert(Money.dollar(5) != Money.franc(5))
end
def test_currency
assert_equal(:USD, Money.dollar(1).currency())
assert_equal(:CHF, Money.franc(1).currency())
end
end
end
Related Pages: DiaryDan20051116
system revision 1.162