On Github suranyami / dci-presentation
class Account < ActiveRecord::Base validate :name, presence: true validate :amount, presence: true, numericality: true end
class Account < ActiveRecord::Base validate :name, presence: true validate :amount, presence: true, numericality: true def transfer(trans_amt, other) self.amount -= trans_amt other.amount += trans_amt end end
class TransferContext def initialize(source_id, dest_id) @source = Account.find(source_id) @destination = Account.find(dest_id) end def execute(amount) @source.amount -= amount @destination.amount += amount end end
describe TransferContext do before do @source = Account.new(amount: 2000) @destination = Account.new(amount: 0) Account.expects(:find).with(1).returns(@source) Account.expects(:find).with(2).returns(@destination) @transfer = TransferContext.new(1, 2) end describe "executing transfer" do before {@transfer.execute(99)} it "subtracts amount from source, adds to dest" do @source.amount.should eql 1901 @destination.amount.should eql 99 end end end
class AccountController < ActiveSupport::TestCase def transfer transfer_context = TransferContext.new(params[:source], params[:dest]) transfer_context.execute(params(:amount)) end end
class Account < ActiveRecord::Base validate :name, presence: true validate :amount, presence: true, numericality: true end