-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: create custom validator for email uniqueness
- Loading branch information
Showing
2 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |