型号规格中的工厂女孩​​确认验证

时间:2013-04-28 20:37:40

标签: ruby-on-rails activerecord rspec factory-bot

在尝试测试电子邮件确认是否为零时,我遇到了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,这会导致模型的电子邮件属性出现验证异常。但是,由于某些原因,电子邮件属性上没有验证错误导致规范失败。我甚至在 FactoryGirl.build(:user,email_confirmation:nil)之后做了 put 的电子邮件和电子邮件确认,以验证电子邮件确认是否为空(确实如此)。我需要一种方法来验证Factory Girl中的属性确认,并且似乎被卡住了。

2 个答案:

答案 0 :(得分:1)

请访问ActiveRecord上的Rails文档。

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

要在email_confirmation为空时收到确认错误,请向presence

添加:email_confirmation验证

答案 1 :(得分:0)

我想也许

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

应该只是

:presence =&gt;是的,