Created
March 17, 2009 22:35
-
-
Save latompa/80803 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Account < ActiveRecord::Base | |
has_many :balance_transfers | |
has_many :orders | |
def purchase_order(description, cost) | |
begin | |
transaction do | |
balance_transfers.create! :change=>cost | |
orders.create! :description=>description | |
end | |
rescue Exception => ex | |
p "rolling back #{ex.message}" | |
end | |
end | |
end | |
class BalanceTransfer < ActiveRecord::Base | |
belongs_to :account | |
validates_presence_of :account | |
before_save :update_account_balance | |
def update_account_balance | |
if account.balance < change | |
errors.add_to_base("not enough funds") | |
raise "not enough points" | |
else | |
account.update_attribute(:balance,(account.balance - change)) | |
end | |
end | |
end | |
class Order < ActiveRecord::Base | |
belongs_to :account | |
validates_presence_of :account | |
validates_presence_of :description | |
end | |
class AccountTest < ActiveSupport::TestCase | |
self.use_transactional_fixtures = false | |
def setup | |
Account.delete_all | |
Order.delete_all | |
BalanceTransfer.delete_all | |
end | |
test "enough funds" do | |
account=Account.create :name=>"test", :balance=>100 | |
order=account.purchase_order "stroberi",50 | |
account.reload | |
assert_equal 50,account.balance | |
assert_equal 1,account.balance_transfers.size | |
assert_equal 1,account.orders.size | |
assert_equal order.description, "stroberi" | |
end | |
test "not enough funds" do | |
account=Account.create! :name=>"test", :balance=>10 | |
account.purchase_order "stroberi",50 | |
account.reload | |
assert_equal 10,account.balance | |
assert_equal 0,account.balance_transfers.size | |
assert_equal 0,account.orders.size | |
end | |
test "invalid order description" do | |
account=Account.create :name=>"test", :balance=>100 | |
account.purchase_order nil,50 | |
account.reload | |
# no point txs should be created | |
assert_equal 0, account.balance_transfers.count | |
assert_equal 0, account.orders.count | |
assert_equal 100,account.balance | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment