Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-4411

Update on root document does not invoke before_save callback correctly in embedded docs with cascade_callbacks: true

    • Type: Icon: Bug Bug
    • Resolution: Duplicate
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 6.1.0
    • Component/s: None
    • None

      class Group
        include Mongoid::Document
        embeds_many :users, cascade_callbacks: true
      end
      
      class User
        include Mongoid::Document
        field :email, type: String
        field :email_md5, type: String
      
        embedded_in :group
      
        before_save :calculate_md5
      
        def calculate_md5
          self.email_md5 = Digest::MD5.hexdigest(email)
        end
      end
      
      require 'rails_helper'
      
      RSpec.describe Group, type: :model do
        before do
          @group= Group.new(users: [{ email: 'test' }])
          @group.save
        end
      
        it 'saves email_md5 on create' do
          email_md5 = @group.reload.users[0].email_md5
          expect(email_md5).to eq Digest::MD5.hexdigest('test')
        end
      
        describe 'on update' do
          before do
            @group.update(users: [{ email: 'test2' }])
          end
      
          it 'calculate email_md5' do
            email_md5 = @group.users[0].email_md5
            expect(email_md5).to eq Digest::MD5.hexdigest('test2')
          end
      
          it 'actually saves email' do
            email = @group.reload.users[0].email
            expect(email).to eq 'test2'
          end
      
          it 'actually saves email_md5' do
            email_md5 = @group.reload.users[0].email_md5
            expect(email_md5).not_to be_blank
          end
        end
      end
      

      The last test fails. It does call the callback but not actually saves it to the database.
      https://github.com/aptx4869/dummy

            Assignee:
            emily.stolfo Emily Stolfo
            Reporter:
            itCHIcKe jl [X]
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: