diff --git a/spec/integration/validations_spec.rb b/spec/integration/validations_spec.rb new file mode 100644 index 0000000000..135d167635 --- /dev/null +++ b/spec/integration/validations_spec.rb @@ -0,0 +1,39 @@ +# rubocop:todo all +# frozen_string_literal: true + +require 'spec_helper' +require_relative './validations_spec_models' + +describe 'validations' do + + context 'when validating presence of has_and_belongs_to_many association' do + let(:company) { ValidationsSpecModels::Company.create! } + let(:client) { ValidationsSpecModels::Client.create!(companies: [company]) } + + context 'when updating the association' do + it 'raises an error' do + expect { client.update!(companies: []) }.to raise_error(Mongoid::Errors::Validations) + end + + it 'does not persist the changes' do + expect { client.update!(companies: []) rescue nil }.not_to change { client.reload.companies } + end + end + end + + + context 'when validating presence of has_many association' do + let(:apartment) { ValidationsSpecModels::Apartment.create! } + let(:building) { ValidationsSpecModels::Building.create!(apartments: [apartment]) } + + context 'when updating the association' do + it 'raises an error' do + expect { building.update!(apartments: []) }.to raise_error(Mongoid::Errors::Validations) + end + + it 'does not persist the changes' do + expect { building.update!(apartments: []) rescue nil }.not_to change { building.reload.apartments } + end + end + end +end diff --git a/spec/integration/validations_spec_models.rb b/spec/integration/validations_spec_models.rb new file mode 100644 index 0000000000..0aaa14502e --- /dev/null +++ b/spec/integration/validations_spec_models.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +module ValidationsSpecModels + class Company + include Mongoid::Document + end + + class Client + include Mongoid::Document + + has_and_belongs_to_many :companies, class_name: 'ValidationsSpecModels::Company' + validates :companies, presence: true + end + + class Building + include Mongoid::Document + has_many :apartments, class_name: 'ValidationsSpecModels::Apartment' + validates :apartments, presence: true + end + + class Apartment + include Mongoid::Document + belongs_to :building, class_name: 'ValidationsSpecModels::Building' + end +end