rspec重新加载对象清除has_many集合

时间:2012-06-10 23:19:19

标签: 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..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

1 个答案:

答案 0 :(得分:0)

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

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