重复用户测试失败?

时间:2017-01-12 16:40:03

标签: ruby-on-rails ruby ruby-on-rails-5

我正在关注一个教程,到目前为止,我的测试已经成功,直到我为电子邮件地址的唯一性编写了最后一个测试

test / models / user_test.rb

require 'test_helper'

class UserTest < ActiveSupport::TestCase

.
.   
.


  test "email addresses should be unique" do
    duplicate_user = @user.dup
    duplicate_user.email = @user.email.upcase
    @user.save
    assert_not duplicate_user.valid?
  end

模型本身包括以下验证。

应用/模型/ user.rb

class User < ApplicationRecord
  before_save { self.email = email.downcase! }
  validates :name,  presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
                     has_secure_password
  validates :password, presence: true, length: { minimum: 6 }
end

上次测试我得到一个布尔错误

" test_email_addresses_should_be_unique#UserTest (0.87s)
        Expected true to be nil or false"

我将唯一性验证设置为省略区分大小写。因此,重复用户不应该失效吗?

完整的测试: 的测试/模型/ user_test.rb

require 'test_helper'

class UserTest < ActiveSupport::TestCase

  def setup
    @user = User.create(name: "Example User", email: "user@example.com",
                     password: "foobar", password_confirmation: "foobar")
  end

  test "should be valid" do
    assert @user.valid?
  end

  test "name should not be too long" do
    @user.name = "a" * 51
    assert_not @user.valid?
  end

  test "email should not be too long" do
    @user.email = "a" * 244 + "@example.com"
    assert_not @user.valid?
  end

   test "email validation should accept valid addresses" do
    valid_addresses = %w[user@example.com USER@foo.COM A_US-ER@foo.bar.org
                         first.last@foo.jp alice+bob@baz.cn]
    valid_addresses.each do |valid_address|
      @user.email = valid_address
      assert @user.valid?, "#{valid_address.inspect} should be valid"
    end
  end
     test "email validation should reject invalid addresses" do
    invalid_addresses = %w[user@example,com user_at_foo.org user.name@example.
                           foo@bar_baz.com foo@bar+baz.com]
    invalid_addresses.each do |invalid_address|
      @user.email = invalid_address
      assert_not @user.valid?, "#{invalid_address.inspect} should be invalid"
    end
  end

  test "email addresses should be unique" do
    duplicate_user = @user.dup
     duplicate_user.email = @user.email.upcase
    @user.save!
    assert_not duplicate_user.valid?
  end

1 个答案:

答案 0 :(得分:2)

我在我的机器上试用了你的代码,似乎问题出现在before_save回调中。

bang版本downcase!修改字符串本身,如果有任何更改(即,任何字符下载)返回结果,否则返回nil

虽然downcase返回字符串的副本,其中所有字符都是小写的。因此,您可以使用以下方法之一:before_save { self.email = email.downcase }before_save { email.downcase! }