Validate uniqueness of Active Record attribute
11 March 2022 (Updated 24 April 2022)
Assuming, you have RSpec and Shoulda Matchers installed, you can add the following test:
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe User, type: :model do
describe 'validations' do
subject { build(:user) }
it { is_expected.to validate_presence_of(:email) }
it { is_expected.to validate_uniqueness_of(:email).case_insensitive }
end
end
To make test pass, you’d include the following in the User
model:
# frozen_string_literal: true
class User < ApplicationRecord
validates :email, presence: true, uniqueness: { case_sensitive: false }
end
Sources
Tagged:
Rails testing
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment