所以在 Rails 中,我为电子邮件编写了这些验证:
validates :email, presence: true, uniqueness: true
validates_format_of :email, :with => /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/
当我尝试使用错误的电子邮件提交内容时,这是有效的,因为它向我发送了一个错误,但是当我尝试像这样测试它时:
test "should not save if email is not valid" do
slogan = Slogan.create(firstname: 'tristan', lastname: 'vermeesch', email: 'titivermeeschgmail.com', slogan: 'Test')
assert slogan.valid?, "Tried to save with an email that is not valid"
end
测试失败,有人可以帮忙吗?
最佳答案
如果您正在尝试测试您的模型不应该被保存并且在提供错误的电子邮件时它应该有错误,您可以使用 valid?方法和错误?属性(property)。 您的测试将是这样的:
test "should not save if email is not valid" do
slogan = Slogan.create(firstname: 'tristan', lastname: 'vermeesch', email: 'titivermeeschgmail.com', slogan: 'Test')
assert_not_nil slogan.errors[:email]
end
关于ruby-on-rails - 在 rails TestCase 中检查正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56475872/