Can somebody explain when to reload an ActiveRecord

Hi all,

I’ve the following test method in my controller_test which increment the
‘qty’ attribute in a has_many association, ‘sa_report_products’. The
‘item_count’ method returns the sum of all qty’s in
‘sa_report_products’:

def test_add_product_to_report
sa_rpt = SaReport.find(1)
assert_equal 3, c = sa_rpt.item_count, ‘initial count is 3’
assert_equal 2, sa_rpt.sa_report_products[0].qty, ‘initial qty is 2’
post :add_item, :id => sa_rpt.id, :new_product_item_id => 1,
:new_product_item_qty => 3
sa_rpt.reload # MUST HAVE THIS TO WORK, WHY??
assert_equal 2, sa_rpt.sa_report_products.length, ‘still have 2 item
lines’
assert_equal 5, sa_rpt.sa_report_products[0].qty, ‘3 added’
sa_rpt.update
assert_equal c + 3, sa_rpt.item_count, ‘3 added’
end
end

The test failed if I leave out the “sa_rpt.reload” line, that is
“sa_rpt.sa_report_products[0].qty” is still 2, not 5.

My problem is I don’t really understand when I needed to reload an
ActiveRecord, can somebody explain?

Thank
Jack Hung

You generally use the Reload method in your test harnesses. You have set
sa_rpt to the item with id=1. After the post, the data inside the
database has changed wrt to id=1. sa_rpt does not re-populate itself
automatically if the database changes, so you need to do a Reload to get
the latest data from the database if you want to make use of the new
data - which you are because you want to run tests against this data.