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

德维尔格雷

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

码:

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

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

It-Z

首先,您应该信任单独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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章