diff --git a/spec/mongoid/touchable_spec.rb b/spec/mongoid/touchable_spec.rb index 578f22ed6c..287e363839 100644 --- a/spec/mongoid/touchable_spec.rb +++ b/spec/mongoid/touchable_spec.rb @@ -733,6 +733,81 @@ end end + context "when a custom field is specified" do + + shared_examples "updates the child's updated_at" do + + let!(:start_time) { Timecop.freeze(Time.at(Time.now.to_i)) } + + let(:update_time) { Timecop.freeze(Time.at(Time.now.to_i) + 2) } + + after do + Timecop.return + end + + let!(:label) do + TouchableSpec::Referenced::Label.create! + end + + let(:band) do + TouchableSpec::Referenced::Band.create!(label: label) + end + + before do + update_time + band.send(meth) + end + + it "updates the child's timestamp" do + expect(band.updated_at).to eq(update_time) + expect(band.reload.updated_at).to eq(update_time) + end + end + + shared_examples "updates the parent's custom field and updated_at" do + + let!(:start_time) { Timecop.freeze(Time.at(Time.now.to_i)) } + + let(:update_time) { Timecop.freeze(Time.at(Time.now.to_i) + 2) } + + after do + Timecop.return + end + + let!(:label) do + TouchableSpec::Referenced::Label.create! + end + + let!(:band) do + TouchableSpec::Referenced::Band.create!(label: label) + end + + before do + update_time + band.send(meth) + end + + it "updates the parent's custom field" do + expect(label.bands_updated_at).to eq(update_time) + expect(label.reload.bands_updated_at).to eq(update_time) + end + + it "updates the parent's timestamp" do + expect(label.updated_at).to eq(update_time) + expect(label.reload.updated_at).to eq(update_time) + end + + end + + [:save, :destroy, :touch].each do |meth| + context "with #{meth} on referenced associations" do + let(:meth) { meth } + include_examples "updates the child's updated_at" unless meth == :destroy + include_examples "updates the parent's custom field and updated_at" + end + end + end + context 'multi-level' do let!(:start_time) { Timecop.freeze(Time.at(Time.now.to_i)) } diff --git a/spec/mongoid/touchable_spec_models.rb b/spec/mongoid/touchable_spec_models.rb index 4dae9c4464..31fabf1e09 100644 --- a/spec/mongoid/touchable_spec_models.rb +++ b/spec/mongoid/touchable_spec_models.rb @@ -150,5 +150,21 @@ class Sofa embedded_in :floor, touch: true, class_name: "TouchableSpec::Referenced::Floor" end + + class Label + include Mongoid::Document + include Mongoid::Timestamps + + field :bands_updated_at, type: DateTime + has_many :bands, class_name: "TouchableSpec::Referenced::Band" + end + + class Band + include Mongoid::Document + include Mongoid::Timestamps + + belongs_to :label, touch: :bands_updated_at, class_name: "TouchableSpec::Referenced::Label" + end + end end