在销毁父级时调用或不调用回调函数(依赖:: :)

时间:2017-03-12 21:14:24

标签: ruby-on-rails callback mocha minitest

我想知道当父级通过before/after_destroy触发销毁时,是否有一种方法可以测试子对象的回调(dependent: :destroy)?显然,我们无法访问在销毁过程中创建的对象。

如果有帮助,我正在使用MiniTest和Mocha gem。我怀疑它可能与模仿关系以及方法有关?

2 个答案:

答案 0 :(得分:1)

取决于我们希望如何严格隔离。

我们假设我们在Rails 4中有这个例子:

class Post < ActiveRecord::Base
  has_many :comments, dependent: :destroy

  after_destroy :after_destroy_method

  def after_destroy_method
  end
end

class Comment < ActiveRecord::Base
  belongs_to :post
end

无论如何,我建议使用一些隔离,因为Post的模型不负责知道,评论被破坏后会发生什么。因此,测试回调的正确行为应该进入Comment模型测试。

严格隔离:

我们知道如果我们在关系上应用dependent: :destroy,那么Rails将完成其工作并调用回调(它经过测试并且像魅力一样工作)。所以唯一要测试的是:

  • 我们在正确的位置使用dependent: :destroy。为此,我们可以在Post模型测试中使用Shoulda Matchers,如下所示:should have_many(:comments).dependent(:destroy)

没有那么严格的隔离:

在Post模型测试中,它越来越接近集成测试了:

test "calls #after_destroy_method on the comments after a post gets destroyed" do
  post = Post.create title: "Test title"
  Comment.create post: post

  Comment.any_instance.expects(:after_destroy_method)

  post.destroy
end

答案 1 :(得分:0)

您应该测试before / after_destroy块中的转换是否已完成。

是否更新了数据库?被模拟的对象被调用了吗?

相关问题