Testing BigDecimal and sum

Hi

I have the following test:

it “calculates the actual expenditure per month” do
@expense = Expense.new(:name => “rent”, :limit => 100.50)
@expense.save
@expense.transactions << Transaction.new(:t_date =>
Date.civil(2010,01,05), :description => “Payment for rent”, :value =>
300)
@expense.transactions << Transaction.new(:t_date =>
Date.civil(2010,01,10), :description => “Payment for rent”, :value =>
200)
@expense.transactions << Transaction.new(:t_date =>
Date.civil(2010,02,01), :description => “Payment for rent”, :value =>
100)
@expense.actual.should == BigDecimal(‘600’)
end

The actual method in expense looks like this:
def actual
transactions.sum(‘value’)
end

I have noticed that I have to save @expense for this to work, why is
that?
Are the transactions saved when I assign them to the saved @expense
using << ?
Is there a better way to write this test, perhaps without hitting the
database?

My second question is with regards to this line:
@expense.actual.should == BigDecimal(‘600’)

Is that a common way of testing BigDecimal?
What is considered best practices when dealing with this?

Thanks, Daryn

On Dec 26, 4:37pm, Daryn [email protected] wrote:

@expense.transactions << Transaction.new(:t_date =>
transactions.sum(‘value’)
end

I have noticed that I have to save @expense for this to work, why is
that?

because the sum method on an association always does “Select
sum(column_name) from …” so if the objects are unsaved then nothing
is found (Active record’s sum method hides the ruby sum method).
If the expense object isn’t saved then the transactions can’t be saved
since expense_id is not known)

Fred