1
我正在使用before_save調用來更新屬於特定主控的所有記錄。兩者都有一個名爲item_id的字段:使用RSpec和Factory Girl測試before_save
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
原因很有意思。該模型確實在其被成功挽救一個記錄模式的第二個實例的工作,但不會返回到規格:
"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,
}
你知道:
- 爲什麼發生這種情況?
- 我怎樣才能讓這個規範通過?
就是這樣!很簡單,當你知道如何;-)非常感謝。 –