From fa0733f480b658f163acde1512c34fdb3f557e5e Mon Sep 17 00:00:00 2001 From: Alex Turchyn Date: Wed, 28 May 2025 19:11:39 +0300 Subject: [PATCH] improve user email validation --- app/models/user.rb | 2 ++ spec/system/profile_settings_spec.rb | 8 ++++++++ spec/system/setup_spec.rb | 10 ++++++++++ spec/system/team_settings_spec.rb | 17 +++++++++++++++++ 4 files changed, 37 insertions(+) diff --git a/app/models/user.rb b/app/models/user.rb index e8e5f879..f840ca7d 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -73,6 +73,8 @@ class User < ApplicationRecord scope :archived, -> { where.not(archived_at: nil) } scope :admins, -> { where(role: ADMIN_ROLE) } + validates :email, format: { with: /\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\z/ } + def access_token super || build_access_token.tap(&:save!) end diff --git a/spec/system/profile_settings_spec.rb b/spec/system/profile_settings_spec.rb index 7b977d2d..3c05a664 100644 --- a/spec/system/profile_settings_spec.rb +++ b/spec/system/profile_settings_spec.rb @@ -33,6 +33,14 @@ RSpec.describe 'Profile Settings' do expect(user.last_name).to eq('Beckham') expect(user.email).to eq('david.beckham@example.com') end + + it 'does not update if email is invalid' do + fill_in 'Email', with: 'devid+test@example' + + all(:button, 'Update')[0].click + + expect(page).to have_content('Email is invalid') + end end context 'when changes password' do diff --git a/spec/system/setup_spec.rb b/spec/system/setup_spec.rb index 5235c9b5..da4a37da 100644 --- a/spec/system/setup_spec.rb +++ b/spec/system/setup_spec.rb @@ -51,6 +51,16 @@ RSpec.describe 'App Setup' do end context 'when invalid information' do + it 'does not setup the app if the email is invalid' do + fill_setup_form(form_data.merge(email: 'bob@example-com')) + + expect do + click_button 'Submit' + end.not_to(change(User, :count)) + + expect(page).to have_content('Email is invalid') + end + it 'does not setup the app if the password is too short' do fill_setup_form(form_data.merge(password: 'pass')) diff --git a/spec/system/team_settings_spec.rb b/spec/system/team_settings_spec.rb index 0286267f..01ce568f 100644 --- a/spec/system/team_settings_spec.rb +++ b/spec/system/team_settings_spec.rb @@ -92,6 +92,23 @@ RSpec.describe 'Team Settings' do end end + it 'does not allow to create a new user with an invalid email' do + click_link 'New User' + + within '#modal' do + fill_in 'First name', with: 'Joseph' + fill_in 'Last name', with: 'Smith' + fill_in 'Email', with: 'joseph.smith@gmail' + fill_in 'Password', with: 'password' + + expect do + click_button 'Submit' + end.not_to change(User, :count) + + expect(page).to have_content('Email is invalid') + end + end + it 'updates a user' do first(:link, 'Edit').click