【问题标题】:rspec reloading object clears has_many collectionrspec 重新加载对象清除 has_many 集合
【发布时间】:2012-06-13 22:43:01
【问题描述】:

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

【问题讨论】:

    标签: activerecord rspec rspec-rails


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2013-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多