I have intermittently (on various projects) had problems with rspec reloading an ActiveRecord object and then having the associated objects cleared, too.
An example of a failing spec that “should” work is as follows (ignore “goodness” of tests, this is a simplified example):
# Message has_many :message_attachments
# MessageAttachment belongs_to :message
describe Message, 'instance' do
before(:each) do
@it = Factory(:message)
(1..3).each do
@it.message_attachments << Factory(:message_attachment, :message => @it)
end
end
it 'should order correctly' do
# This test will pass
@it.message_attachments.collect(&:id).should == [1, 2, 3]
end
it 'should reorder correctly' do
@it.reorder_attachments([6, 4, 5])
@it.reload
# @it.message_attachments is [] now.
@it.message_attachments.collect(&:id).should == [6, 4, 5]
end
end
Strangely, to fix this I have to create the associated object with a defined parent object and also attach it to the parent object’s collection: