【问题标题】:Factory Girl Confirmation Validation in Model Spec模型规范中的工厂女孩​​确认验证
【发布时间】: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


    【解决方案1】:

    请通过 ActiveRecord 上的 Rails 文档。

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

    若要在email_confirmation 为空时得到确认错误,请将presence 验证添加到:email_confirmation

    【讨论】:

    • 谢谢,我不敢相信我没有想到 nil vs blank 的场景。你拯救了我的一天!
    • 很高兴它对你有用。 :) 在常规的 RSpec 测试过程中,我遇到了一些挫折。
    【解决方案2】:

    我觉得可能

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

    应该是

    :存在 => 真,

    【讨论】:

    • 电子邮件是我创建的自定义验证器,我会将该代码添加到我的原始帖子中,以免混淆。
    猜你喜欢
    • 2012-03-08
    • 1970-01-01
    • 2013-05-19
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多