Skip to content

Instantly share code, notes, and snippets.

@tatey
Created January 14, 2010 10:28
Show Gist options
  • Save tatey/277056 to your computer and use it in GitHub Desktop.
Save tatey/277056 to your computer and use it in GitHub Desktop.
# Learning Ruby. A consice implementation of the Bank Account example.
# http://gist.github.com/277023
require 'test/unit'
class Account
attr_reader :number, :name, :balance
@@number = 0
def initialize(name)
@number = @@number += 1
@name = name
@balance = 0
end
def deposit(amount)
@balance += amount
end
def withdraw?(amount)
return false if amount > @balance
@balance -= amount
true
end
def calculate_interest(rate)
12.times.inject(@balance) { |b, m| b += b * rate } - @balance
end
end
class TransactionAccount < Account
TRANSACTION_FEE = 0.30
def withdraw?(amount)
return false unless super(amount)
@balance -= TRANSACTION_FEE
true
end
end
class TestAccount < Test::Unit::TestCase
def setup
@account1 = Account.new('Monica')
end
def test_number_should_be_incremented_at_initialization
assert @account1.number < @account2.number
end
def test_name_should_be_defined_at_initialization
assert_equal 'Monica', @account1.name
end
def test_balance_should_be_zero_at_initialization
assert @account1.balance.zero?
end
def test_deposit_should_increase_balance
@account1.deposit(100)
assert_equal 100, @account1.balance
end
def test_withdraw_should_be_false_when_insufficient_balance
assert ! @account1.withdraw?(150)
end
def test_withdraw_should_be_true_when_sufficient_balance
@account1.deposit(100)
assert @account1.withdraw?(25)
assert_equal 75, @account1.balance
end
def test_calculate_interest
@account1.deposit(100)
assert_equal '79.5856326022129', @account1.calculate_interest(0.05).to_s
end
end
class TestTransactionAccount < Test::Unit::TestCase
def test_withdraw_should_charge_transaction_fee
@account1 = TransactionAccount.new('Monica')
@account1.deposit(100)
@account1.withdraw?(100)
assert_equal -0.30, @account1.balance
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment