0

我间歇性地(在各种项目中)遇到 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
4

1 回答 1

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
于 2012-06-10T23:19:19.953 回答