Skip to content

Commit

Permalink
Add tests for the issue
Browse files Browse the repository at this point in the history
  • Loading branch information
comandeo-mongo committed Nov 7, 2023
1 parent 67c8035 commit a023a7c
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
39 changes: 39 additions & 0 deletions spec/integration/validations_spec.rb
Original file line number Diff line number Diff line change
@@ -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
25 changes: 25 additions & 0 deletions spec/integration/validations_spec_models.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit a023a7c

Please sign in to comment.