【发布时间】:2013-04-22 11:09:24
【问题描述】:
我在尝试测试电子邮件确认是否为零时遇到了 Factory Girl 问题。
这是我的模型规格 (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
这是我的模型(user.rb)
class User < ActiveRecord::Base
attr_accessible :email,
:email_confirmation
validates :email,
:confirmation => true,
:email => {
:presence => true
},
:uniqueness => {
:case_sensitive => false
}
end
这是我的工厂(users.rb)
FactoryGirl.define do
factory :user do
email { Faker::Internet.email }
end
end
自定义电子邮件验证器(在配置/初始化程序中)
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
我希望 在没有电子邮件确认的情况下无效 规范能够通过,因为我将电子邮件确认设置为 nil,这会导致模型的 email 属性出现验证异常。但是,由于某种原因,email 属性上没有验证错误导致规范失败。我什至在 FactoryGirl.build(:user, email_confirmation: nil) 之后对电子邮件和电子邮件确认进行了 puts 以验证电子邮件确认是否为空(确实如此)。我需要一种方法来验证 Factory Girl 中的属性确认,但似乎卡住了。
【问题讨论】:
标签: ruby-on-rails activerecord rspec factory-bot