【发布时间】: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