【问题标题】:Rspec does not execute a "before_destroy" callbackRspec 不执行“before_destroy”回调
【发布时间】:2022-08-14 18:13:22
【问题描述】:

在我的书本模型中,我有一个“before_destroy”回调(带有可能丑陋的方法),如下所示:

  before_destroy :destroy_fallback
  private

  def destroy_fallback
    unless self.fallback?
      format_fallback = BookFormat.find_by(fallback: true)
      Book.where(book_format_id: self.id).update(book_format_id: format_fallback.id)
    else
      errors.add(:base, :undestroyable)
      throw :abort
    end
  end

然而,当我测试这确实发生时,它似乎没有。这里的这个规范会导致一个错误(说两个 id\'s 不一样): 需要 \'rails_helper\'

RSpec.describe BookFormat, type: :model do
  before(:all) do
    @book = create(:hobbit)
    @book_format_default = create(:not_defined)
  end

  it \'should reassign to the fallback book_format if their book_format is deleted\' do
    format = @book.book_format
    format.destroy
    expect(@book.book_format.id).to eq(@book_format_default.id)
  end
end

看起来destroy_fallback 从未执行过,即没有使用before_destroy 回调?在开发中,当我通过网站执行此操作时 - 一切似乎都按预期工作。

  • 您可能需要在规范中重新加载@book.book_format 对象(也可能是@book 对象)...所以expect(@book.reload.book_format.reload.id).to... etc.
  • 在回调中放置puts 语句以查看它是否被实际调用,它可能被调用但测试并未确认。我认为它必须被调用,因为它在网页上工作。
  • 就是这样 - 一个简单的@book.reload.book_format.id 成功了 :) 谢谢。

标签: ruby-on-rails activerecord rspec


【解决方案1】:

可能只是复制粘贴错误,但您的模型中似乎没有 destroy_fallback 方法。

确保您实际上是在定义一个方法:

class Book < ApplicationRecord
 before_destroy :destroy_fallback

  ...

  private
  
  def destroy_fallback
    unless self.fallback?
      format_fallback = BookFormat.find_by(fallback: true)
      Book.where(book_format_id: self.id).update(book_format_id: format_fallback.id)
    else
      errors.add(:base, :undestroyable)
      throw :abort
    end
  end
end

而且,我发现 unless - else 真的很难推理。

class Book < ApplicationRecord
 before_destroy :destroy_fallback

  ...

  private
  
  def destroy_fallback
    if self.fallback?
      errors.add(:base, :undestroyable)
      throw :abort
    else
      format_fallback = BookFormat.find_by(fallback: true)
      Book.where(book_format_id: self.id).update(book_format_id: format_fallback.id)
    end
  end
end

【讨论】:

  • 谢谢。第一个观察与我的复制/粘贴错误有关:)。第二个当然是正确的 - 如果您处于编程流程中,就会发生这种情况。
  • 如果这不能解决问题,您可以使用实际代码更新您的问题吗?
  • Les 的上述答案修复了它 - 我需要在规范中重新加载 @book。但我也更正了代码。
猜你喜欢
  • 1970-01-01
  • 2017-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多