目の前に僕らの道がある

勉強会とか、技術的にはまったことのメモ

テスト駆動開発入門をRubyで写経してみた。11

11章で実施したこと

  • Dollarクラス、Francクラスの削除

money.rb

#!/usr/bin/ruby
#coding: utf-8
# テスト駆動開発入門11章 諸悪の根源
class Money
  attr_accessor :amount, :currency
  protected :amount

  def initialize(amount, currency)
    @amount = amount
    @currency = currency
  end

  def ==(other)
    return @amount == other.amount && @currency == other.currency
  end

  def *(multiplier)
    return Money.new(@amount * multiplier, @currency)
  end

  def self.franc(amount)
    return Money.new(amount, "CHF")
  end

  def self.dollar(amount)
    return Money.new(amount, "USD")
  end
end

money_test.rb

#!/usr/bin/ruby
#coding: utf-8
# テスト駆動開発入門11章 諸悪の根源
require 'test/unit'
require 'money'

class TestMoney < Test::Unit::TestCase
  def test_multiplication
    five = Money.dollar(5)
    assert_equal(Money.dollar(10), five * 2)
    assert_equal(Money.dollar(15), five * 3)
  end

  def test_equality
    assert(Money.dollar(5) == Money.dollar(5))
    assert(Money.dollar(5) != Money.dollar(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