我有一个after_destroy
回调函数,希望返回nil
,但仍然有一个值。
class WeighIn < ActiveRecord::Base
belongs_to :check_in
after_destroy :add_employee_weightloss
def add_employee_weightloss
p self.check_in.weigh_in.present? # returns true
end
end
规格:
it "employee weightloss" do
ci = CheckIn.create()
wi = WeighIn.create(check_in_id: ci.id)
wi.destroy
expect(wi.reload).to eq(nil) # returns wi instead of nil
end
答案 0 :(得分:1)
您应该改用destroyed?
(或exists?
或persisted?
),因为present?
仅检查对象是否存在,这是销毁后的正确行为( destroy
本身会返回已删除的对象。
def add_employee_weightloss
p check_in.weigh_in.destroyed?
end
此外,您不应使用以下内容:
expect(wi.reload).to eq(nil)
如果wi
被销毁,您将获得ActiveRecord::RecordNotFound
而不是nil
的例外。您可以尝试以下操作:
it "employee weightloss" do
wi = WeighIn.create(check_in: CheckIn.create)
wi.destroy
expect(wi.destroyed?).to eq(true)
end