Skip to content

Instantly share code, notes, and snippets.

@deepak
Last active December 10, 2015 04:28
Show Gist options
  • Save deepak/4380666 to your computer and use it in GitHub Desktop.
Save deepak/4380666 to your computer and use it in GitHub Desktop.
class BooleanValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless is_a_boolean? value
record.errors[attribute] << (options[:message] || "is not valid")
end
end
def is_a_boolean? value
!!value == value
end
end
require 'active_model'
require_relative '../../app/validators/boolean_validator'
class Person
attr_accessor :foobar
include ActiveModel::Validations
validates :foobar, :boolean => true
end
describe BooleanValidator do
subject { Person.new }
it "is valid if attribute is true" do
subject.foobar = true
expect(subject.valid?).to eq true
end
it "is valid if attribute is false" do
subject.foobar = false
expect(subject.valid?).to eq true
end
it "is not valid if attribute is a string" do
subject.foobar = "hello"
expect(subject.valid?).to eq false
end
it "is not valid if attribute is a string having a number" do
subject.foobar = "1"
expect(subject.valid?).to eq false
subject.foobar = "a1"
expect(subject.valid?).to eq false
end
it "is not valid if attribute is an integer" do
subject.foobar = 1
expect(subject.valid?).to eq false
end
end
# https://github.com/thoughtbot/factory_girl/wiki/Testing-all-Factories-(with-RSpec)
require 'spec_helper'
describe 'validate FactoryGirl factories' do
FactoryGirl.factories.each do |factory|
context "with factory for :#{factory.name}" do
subject { FactoryGirl.build(factory.name) }
it "is valid" do
subject.should be_valid, subject.errors.full_messages
end
end
end
end
require_dependency 'boolean_validator'
class Loan < ActiveRecord::Base
validates :borrower_male, boolean: true, presence: true
end
FactoryGirl.define do
factory :loan do
borrower_male false
end
end
@deepak
Copy link
Author

deepak commented Dec 26, 2012

factory_spec.rb fails even though boolean_validator_spec.rb is a success. why ?

$ rspec spec/models/factory_spec.rb

validate FactoryGirl factories with factory for :loan is valid
     Failure/Error: subject.should be_valid, subject.errors.full_messages
     []

@deepak
Copy link
Author

deepak commented Dec 27, 2012

fixed. check the webapp project

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment