我目前正在遵循有关Ruby on Rails的Michael Hartl教程。每次我运行一个模型时:测试由于电子邮件的唯一性而失败。即使我已经在模型中说明了这一点。我想在开始将数据添加到Web应用程序之前进行修复。
这是我的用户.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-zd-.]+ : 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-zd-]+(.[a-zd-]+)*.[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
在您的断言调用duplicate_user.save
之前。这将触发该模型上的验证。