我试图在rails上使用区分大小写的唯一性并且测试失败

时间:2018-04-01 22:37:52

标签: ruby-on-rails testing validates-uniqueness-of

我目前正在关注有关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

1 个答案:

答案 0 :(得分:1)

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