【问题标题】:When is the validator of email uniqueness trigerred?电子邮件唯一性验证器何时触发?
【发布时间】:2013-03-12 16:04:50
【问题描述】:

我有一个关于this test from the Michael Hartl tutorial 的问题:

型号:

class User < ActiveRecord::Base
  .
  .
  .
  validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
                    uniqueness: true
end

测试:

require 'spec_helper'

describe User do

  before do
    @user = User.new(name: "Example User", email: "user@example.com")
  end
  .
  .
  .
  describe "when email address is already taken" do
    before do
      user_with_same_email = @user.dup
      user_with_same_email.email = @user.email.upcase
      user_with_same_email.save
    end

    it { should_not be_valid }
  end
end

我对电子邮件唯一性验证器的理解是它不能在数据库中添加两次。但在这个测试中,User 只是用一个 new 实例化,而不是一个 create。

所以这就是我认为会发生的事情:

  • @user = User.new(仅在记忆中)
  • ...
  • user_with_same_email = @user.dup 我们内存中有两个用户
  • ...
  • user_with_same_email.save 我们将第一个用户插入到数据库中,所以它应该是有效的,但测试 it { should_not be_valid } 通过了。

我做错了什么?

【问题讨论】:

    标签: validation ruby-on-rails-3.2


    【解决方案1】:

    真正发生的事情:

    before:

    • @user = User.new(仅在记忆中)

    describe

    • user_with_same_email = @user.dup 我们内存中有两个用户
    • user_with_same_email.save 我们在数据库中插入第一个用户,所以它应该是有效的,它是!但这不是这里要测试的内容

    it

    • should_not be_valid 在@user 上调用.valid?,由于我们刚刚插入了具有相同电子邮件的用户,@user 无效。所以测试通过了。

    【讨论】:

    • 好答案!同样重要的是要注意,在向数据库发送非常快的INSERT 订单的情况下,它们都将通过内存中的验证,因此两者都将是INSERTed。正如这里所讨论的stackoverflow.com/questions/14942608/…
    猜你喜欢
    • 2021-08-22
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    相关资源
    最近更新 更多