Skip to content

Instantly share code, notes, and snippets.

@urbanautomaton
Created March 16, 2012 14:40
Show Gist options
  • Save urbanautomaton/2050345 to your computer and use it in GitHub Desktop.
Save urbanautomaton/2050345 to your computer and use it in GitHub Desktop.
class Brand < ActiveRecord::Base
validates_with BrandValidator
# ...
end
class BrandValidator < ActiveModel::Validator
def validate(record)
must_not_be_white_and_blacklisted(record)
must_not_be_synonym_of_self(record)
end
private
def must_not_be_white_and_blacklisted(record)
if record.whitelisted && record.blacklisted
record.errors[:status] << 'must not be white- and blacklisted'
end
end
def must_not_be_synonym_of_self(record)
if record.synonym == record
record.errors[:synonym] << 'is itself'
end
end
end
require 'active_model'
require 'support/validations'
require_relative '../../app/validators/brand_validator'
class Validatable
include ActiveModel::Validations
validates_with BrandValidator
end
VALID_ATTRIBUTES = {
:whitelisted => false,
:blacklisted => false,
:synonym => nil,
}
describe BrandValidator do
subject { Validatable.new }
before { subject.stub(VALID_ATTRIBUTES) }
context 'in normal operation' do
it { should be_valid }
end
context 'with a brand that is both white- and blacklisted' do
before { subject.stub(:whitelisted => true, :blacklisted => true) }
it { should have(1).error_on(:status) }
end
context 'with a brand that is a synonym of itself' do
before { subject.stub(:synonym => subject) }
it { should have(1).error_on(:synonym) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment