0

我目前正在关注关于 ruby​​ on rails 的 Michael Hartl 教程。每次我运行模型时:测试由于电子邮件的唯一性而失败。尽管我已经在模型中说明了这一点。我想在开始向 Web 应用程序添加数据之前解决这个问题。

这是我的 user.rb

before_save { self.email = email.downcase! }
validates :name, presence: true, length: { maximum: 50 }

# Regex explaination below
# / :   start of regex | \A : match start of a string
# [\w+\-.]+ : at least one word character, plus, hyphen, or dot
# @ : literal “at sign” | [a-z\d\-.]+ : at least one letter, digit, hyphen, 
or dot
# \. : literal dot | [a-z]+ : at least one letter
# \z : match end of string | / : end of regex
# i :  case-insensitive
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
                uniqueness: { case_sensitive: false },
                format: { with: VALID_EMAIL_REGEX }

这是我的 user_test.rb

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
4

1 回答 1

1

在您的断言调用之前duplicate_user.save。这将触发对该模型的验证。

于 2018-04-02T02:28:24.070 回答