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

问题描述 投票:1回答:2

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

码:

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

你能帮助我理解我应该如何测试这个嵌入式文档回调?

ruby rspec mongoid
2个回答
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

0
投票

您的代码看起来是正确的,但Mongoid中存在许多与持久性回调相关的未解决问题。确保在正常操作中调用回调(即从Rails控制台保存帖子时)。

© www.soinside.com 2019 - 2024. All rights reserved.