1
votes

I'm trying to create a test to check if my post's embedded document(author) call to it callback method.

Code:

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

test:

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

when i'm trying to run this rspec - i got

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

Can you guys help me understand how should I test this embedded document callbacks?

2
What is the exact error. - zeitnot
You're trying to test Rails and/or Mongoid code. My advice is to not do this. Just rely on the fact that the Rails and Mongoid teams wrote sufficient tests and trust those tests. - aridlehoover
Zeitnot - the exact error in the post. - dvirgre
aridlehoover - i want to make sure the callback after_save exists in the model (making sure no one will delete it by mistake and so on..) - dvirgre
Then test the outcome of the after_save. - aridlehoover

2 Answers

0
votes

Your code looks correct but there is a number of outstanding issues in Mongoid related to callbacks in persistence. Ensure the callback is called in normal operation (i.e. when you save a post from a Rails console).

0
votes

First of all, you should trust mongoid to call after_save and test my_callback_method in isolation.

Now, as said in the comments, that you want to check if someone deleted the after_save, you can add a test for:

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