我正在查看 Michael Hartl 的 [Rail 教程] 第 6 章中的一些 RSpec 代码:http://ruby.railstutorial.org/chapters/modeling-users#code:validates_uniqueness_of_email_test 。它是为了测试用户模型的电子邮件属性的唯一性验证方法而编写的。它看起来像这样:
list 6.18。拒绝重复电子邮件地址的测试。 (*spec/models/user_spec.rb*)
require 'spec_helper'
describe User do
before do
@user = User.new(name: "Example User", email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1164627463517469707c617d743f727e7c" rel="noreferrer noopener nofollow">[email protected]</a>")
end
subject { @user }
.
.
.
describe "when email address is already taken" do
before do
user_with_same_email = @user.dup
user_with_same_email.save
end
it { should_not be_valid }
end
end
这是用户模型验证代码:
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: true
我的问题是:验证实际上是如何工作的?有一个用户的电子邮件地址已保存到数据库中,并且 @user 实例上的 Rails 验证在我之前返回为无效。甚至尝试过拯救它? Rails 验证器是否使用当前数据来验证用户的实例,即使它们只是存储在内存中并且当前未尝试添加到数据库中?
最佳答案
be_valid
对 @user
调用 valid?
。这就是 rspec 的工作原理。 valid?
调用 run_validations!
,后者又调用 run_callbacks :validate
。您可以通过源代码跟踪方法链:valid?
在activerecord / lib / active_record / validations.rb 中定义。它在 activemodel / lib / active_model / validations.rb 中调用 super
valid?
这就是它的工作原理。即使未保存,模型也可能有效或无效。如果它从未保存过(new_record?
返回true
),就像您的情况一样,将调用 :create
上的验证。基本上,如果模型有效,则可以保存。如果已保存(new_record?
返回 false
但它可以包含未保存的更改),则会调用 :update
验证。
关于ruby-on-rails - 在尝试保存之前,Rails 模型验证方法是否会在验证过程中检查当前数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10640799/