after_destroy回调声明对象仍然存在

时间:2018-09-11 12:42:15

标签: ruby-on-rails activerecord rspec callback rails-activerecord

我有一个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

1 个答案:

答案 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