Activerecord rspec重新加载对象清除有多个集合

Activerecord rspec重新加载对象清除有多个集合,activerecord,rspec,rspec-rails,Activerecord,Rspec,Rspec Rails,我在不同的项目中间歇性地遇到过rspec重新加载ActiveRecord对象,然后清除关联对象的问题 失败规范的一个例子如下:忽略测试的优点,这是一个简化的例子: # Message has_many :message_attachments # MessageAttachment belongs_to :message describe Message, 'instance' do before(:each) do @it = Factory(:message) (1..

我在不同的项目中间歇性地遇到过rspec重新加载ActiveRecord对象,然后清除关联对象的问题

失败规范的一个例子如下:忽略测试的优点,这是一个简化的例子:

# 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

奇怪的是,要解决这个问题,我必须创建与已定义父对象关联的对象,并将其附加到父对象的集合:

describe Message, 'instance' do
  before(:each) do
    @it = Factory(:message)

    (1..3).each do
      ma = Factory(:message_attachment, :message => @it)
      @it.message_attachments << ma
      ma.save
    end
  end

  it 'should order correctly' do
    @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.collect(&:id).should == [6, 4, 5]
  end
end