Skip to content

Instantly share code, notes, and snippets.

@zelaznik
Created March 27, 2023 19:59
Show Gist options
  • Save zelaznik/09889513d331f82b721123ce4170a641 to your computer and use it in GitHub Desktop.
Save zelaznik/09889513d331f82b721123ce4170a641 to your computer and use it in GitHub Desktop.
require 'rspec/expectations'
=begin
# Example use case in a test suite:
# Make sure to have defined a factory in factory-bot for "job_application"
describe JobApplication, type: :model do
it { is_expected.to enforce_uniqueness_of(:uuid) }
end
=end
RSpec::Matchers.define :enforce_uniqueness_of do |attribute|
# Quick and easy way to make sure that a unique index has been added to the field
# we bypass the ActiveRecord validations when saving the model and check that the
# database throws an error
match do |model|
factory_name = model.class.name.underscore
duplicate_value = SecureRandom.uuid
model_a = create(factory_name, attribute.to_sym => duplicate_value)
model_b = build(factory_name, attribute.to_sym => duplicate_value)
begin
model_b.save(validate: false)
false
rescue PG::UniqueViolation, ActiveRecord::RecordNotUnique => e
true
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment