1

我正在使用 before_save 调用来更新属于特定主控的所有记录。两者都有一个名为 item_id 的字段:

class Master < ActiveRecord::Base
  has_many :records
  before_save :update_records
  def update_records
    self.records.find_each do |r|
      r.item_id = self.item_id
      r.save
    end
  end
end

class Record < ActiveRecord::Base
end

这按预期工作(暂时搁置这样做是否是个好主意)。但是我无法获得通过的 RSpec 测试。这是我尝试过的:

describe Master do
  describe 'before_save' do
    it 'updates records belonging to it' do
      master = FactoryGirl.create(:master, item_id: 1)
      record = FactoryGirl.create(:record, master_id: master.id, item_id: 1)
      master.item_id = 2
      master.save
      record.item_id.should == 2
    end
  end
end

原因很有趣。该模型在 Record 模型的第二个实例上工作,该实例已成功保存,但未返回到规范中:

"MASTER - CREATED IN SPEC"
#<Master:0x007fd0ed55ec20> {
    :id => 26,
    :item_id => 1,
}
"RECORD - CREATED IN SPEC"
#<Record:0x007fd0ea157e40> {
    :id => 16,
    :item_id => 1,
    :master_id => 26,
}
"RECORD - AFTER SAVE IN MODEL"
#<Record:0x007fd0ed2f9a70> {
    :id => 16,
    :item_id => 2,
    :master_id => 26,
}
"MASTER - UPDATED IN SPEC"
#<Master:0x007fd0ed55ec20> {
    :id => 26,
    :item_id => 2,
}
"RECORD - FINAL IN SPEC"
#<Record:0x007fd0ea157e40> {
    :id => 16,
    :item_id => 1,
    :master_id => 26,
}

你知道吗:

  • 为什么会这样?
  • 我怎样才能让这个规范通过?
4

1 回答 1

5

看起来您的记录只是向您显示旧数据,需要刷新。尝试:

record.reload.item_id.should == 2
于 2012-10-21T18:06:23.397 回答