Rspec Mongoid-测试嵌入式文档回调(after_save)

时间:2019-03-05 16:48:34

标签: ruby rspec mongoid

我正在尝试创建一个测试,以检查帖子的嵌入式文档(作者)是否调用了该回调方法。

代码:

class Post
  include Mongoid::Document
  include Mongoid::Timestamps::Created
  include Mongoid::Timestamps::Updated
  {....}
  # relations
  embeds_one :author, cascade_callbacks: true
  accepts_nested_attributes_for :author
  {...}
end

Class Author
  include Mongoid::Document
  include Mongoid::Timestamps::Created
  include Mongoid::Timestamps::Updated

  {...}
   embedded_in :post
   after_save    :my_callback_method

   def save_estimation_logs
     {...}
   end
  {...}
end

测试:

RSpec.describe Author, :type => :model do
  context "Create author on Post" do
    let!(:post) { create(:post, :with_external_author) }
    it "should call after_save method my_callback_method when saving" do
      expect(post.author).to receive(:my_callback_method)
      expect(post.save).to eq true
    end
  end
end

当我尝试运行此rspec时-我得到了

Failure/Error: expect(post.author).to receive(:my_callback_method)

   (#<Author _id: 5c7ea762f325709edac2ae84, created_at: 2019-03-05 16:44:18 UTC, updated_at: 2019-03-05 16:44:18 UTC>). my_callback_method(*(any args))
       expected: 1 time with any arguments
       received: 0 times with any arguments

你们能帮助我了解如何测试此嵌入式文档回调吗?

1 个答案:

答案 0 :(得分:0)

首先,您应该信任mongoid来呼叫after_save并单独测试my_callback_method

现在,如评论中所述,您要检查是否有人删除了after_save,可以为以下项添加测试:

RSpec.describe Author, :type => :model do
  context "Author" do
    it "should define my_callback_method for after_save" do
      result = Author._save_callbacks.select { |cb| cb.kind.eql?(:after) }.collect(&:filter).include?(:my_callback_method)
      expect(result).to eq true
    end
  end
end