Skip to content

Commit

Permalink
feat: create custom validator for email uniqueness
Browse files Browse the repository at this point in the history
  • Loading branch information
TobyRet committed Jan 20, 2025
1 parent 1f5aada commit 8ac157f
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
16 changes: 16 additions & 0 deletions app/validators/email_uniqueness_validator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class EmailUniquenessValidator < ActiveModel::Validator
def validate(record)
return if record.email.blank?

# Check for conflicting records with the same email but different teacher_id
conflicting_period = ECTAtSchoolPeriod
.where(email: record.email)
.where.not(teacher_id: record.teacher_id)
.where.not(id: record.id)
.exists?

if conflicting_period
record.errors.add(:email, "Email address is already in use by another teacher")
end
end
end
36 changes: 36 additions & 0 deletions spec/validators/email_uniqueness_validator_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
require 'rails_helper'

RSpec.describe EmailUniquenessValidator do
let(:test_class) do
Class.new do
include ActiveModel::Model
attr_accessor :id, :email, :teacher_id

validates :email, email_uniqueness: true
end
end

subject { test_class.new(email:) }

let(:teacher_1) { FactoryBot.create(:teacher) }
let(:teacher_2) { FactoryBot.create(:teacher) }
let(:school) { FactoryBot.create(:school) }
let(:email) { "[email protected]" }

context 'when the email is already associated with an existing teacher' do
it 'is not valid' do
FactoryBot.create(:ect_at_school_period, teacher: teacher_1, email:, school:)

expect(subject).not_to be_valid
expect(subject.errors[:email]).to include("Email address is already in use by another teacher")
end
end

context 'when the email is not currently associated with an existing teacher' do
it 'is valid' do
FactoryBot.create(:ect_at_school_period, teacher: teacher_1, email: '[email protected]', school:)

expect(subject).to be_valid
end
end
end

0 comments on commit 8ac157f

Please sign in to comment.