目の前に僕らの道がある

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

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

ちょっと再開します。
PythonよりRubyの方がすっきり書けて楽しいです。

4章で実施したこと

  • amoutのプライベート化

今回はインスタンスメソッドとして呼び出しているので、可視性はprotectedになっています。

money.rb

#!/usr/bin/ruby
#coding: utf-8
# テスト駆動開発入門4章 プライベート化
class Dollar
  attr_accessor :amount
  protected :amount

  def initialize(amount)
    @amount = amount
  end

  def *(multiplier)
    return Dollar.new(@amount * multiplier)
  end

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

money_test.rb

#!/usr/bin/ruby
#coding: utf-8
# テスト駆動開発入門4章 プライベート化
require 'test/unit'
require 'money'

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

  def test_equality
    assert(Dollar.new(5) == Dollar.new(5))
    assert(Dollar.new(5) != Dollar.new(6))
  end
end