after_destroy回调声明对象仍然存在

问题描述 投票:0回答:1

我有一个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
ruby-on-rails activerecord rspec callback rails-activerecord
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.