Skip to content

Instantly share code, notes, and snippets.

@josephbridgwaterrowe
Created January 12, 2016 19:01
Show Gist options
  • Save josephbridgwaterrowe/bf383dbe111740868d86 to your computer and use it in GitHub Desktop.
Save josephbridgwaterrowe/bf383dbe111740868d86 to your computer and use it in GitHub Desktop.
Form entry uniqueness validation and test
# /app/form_objects/my_form_object.rb
class MyFormEntry < FormEntry
attribute :reference, String
validate :unique_reference
def unique_reference
errors.add(:reference, "must be unique") if \
MyObject.find_by(reference: self.reference)
end
end
# /spec/form_objects/my_form_object_spec.rb
require 'rails_helper'
RSpec.describe MyFormObject, type: :model do
describe '#valid?' do
let(:entry) { MyFormObject.new(reference: Faker::Number.number(6)) }
subject { entry }
describe 'custom validators are invoked' do
before do
allow(entry).to receive(:unique_reference)
entry.valid?
end
it { is_expected.to have_received(:unique_reference) }
end
context 'when the reference exists' do
before do
allow(MyObject)
.to receive(:find_by)
.with(reference: entry.reference)
.and_return(double(:my_object))
entry.valid?
end
its(:valid?) { is_expected.to be false }
it 'should add an error to reference' do
expect(entry.errors.messages[:reference]).to be_present
end
end
context 'when the reference does not exist' do
before do
allow(MyObject)
.to receive(:find_by)
.with(reference: entry.reference)
.and_return(nil)
entry.valid?
end
its(:valid?) { is_expected.to be true }
it 'should not add an error to reference' do
expect(entry.errors[:reference]).to be_empty
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment