工厂女工确认确认在模型规格



在尝试测试电子邮件确认是否为nil时,我遇到了工厂女孩的麻烦。


这是我的模型规格(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

自定义电子邮件验证器(在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

我希望在没有电子邮件确认规范通过的情况下无效,因为我将电子邮件确认设置为nil,这应该导致模型的email属性上的验证异常。然而,由于某些原因,在email属性上没有导致规范失败的验证错误。我甚至在FactoryGirl之后做了一个put 的邮件和邮件确认。build(:user, email_confirmation: nil)验证电子邮件确认为空(它确实是空的)。我需要一种方法来验证工厂女孩的属性确认,似乎被卡住了。

请查阅Rails关于ActiveRecord的文档。

:confirmation未验证为null。这里将对相同的email进行验证,因此您可以设置:email_confirmation => ""以通过测试。

email_confirmation为null时,将presence验证添加到:email_confirmation

我想也许

:email => {
  :presence => true
},

应该是

:presence => true,

最新更新