I am having trouble with Factory Girl when trying to test if email confirmation is nil.
Here is my model spec (user_spec.rb)
require 'spec_helper'
describe User do
it "is invalid without an email confirmation" do
user = FactoryGirl.build(:user, email_confirmation: nil)
expect(user).to have(1).errors_on(:email)
end
end
Here is my model (user.rb)
class User < ActiveRecord::Base
attr_accessible :email,
:email_confirmation
validates :email,
:confirmation => true,
:email => {
:presence => true
},
:uniqueness => {
:case_sensitive => false
}
end
Here is my factory (users.rb)
FactoryGirl.define do
factory :user do
email { Faker::Internet.email }
end
end
Custom email validator (in config/initializers)
class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
# If attribute is not required, then return if attribute is empty
if !options[:presence] and value.blank?
return
end
if value.blank?
record.errors[attribute] << 'is required'
return
end
# Determine if email address matches email address regular expression
match = (value.match /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i)
# If email address is not a proper email address
if match == nil
record.errors[attribute] << 'must be a valid email'
# If email address is too short
elsif value.length < 6
record.errors[attribute] << "is too short (minimum is 6 characters)"
# If email address is too long
elsif value.length > 254
record.errors[attribute] << "is too long (maximum is 254 characters)"
end
end
end
I expect the is invalid without an email confirmation spec to pass as I set the email confirmation to nil, which should cause a validation exception on the model's email attribute. However, for some reason there are no validation errors on the email attribute causing the spec to fail. I even did a puts of the email and email confirmation after FactoryGirl.build(:user, email_confirmation: nil) to verify the email confirmation is empty (which it is). I am in need of a way to validate attribute confirmations in Factory Girl and seem to be stuck.