0

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.

4

2 回答 2

1

请仔细阅读 Rails 文档ActiveRecord

:confirmation未验证为 null。它将在此处验证相同email,因此您可以设置:email_confirmation => ""通过测试。

email_confirmation要在为 null时获得确认错误,presence请向:email_confirmation

于 2013-04-28T20:50:37.790 回答
0

我想也许

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

应该只是

:存在=>真,

于 2013-04-28T20:41:04.380 回答