我有一个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
您应该使用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