【发布时间】:2012-05-25 07:54:43
【问题描述】:
我正在查看 Michael Hartl 的 [Rail Tutorial] 的第 6 章中的一些 RSpec 代码:http://ruby.railstutorial.org/chapters/modeling-users#code:validates_uniqueness_of_email_test。它是为了测试用户模型的电子邮件属性的唯一性验证方法而编写的。它看起来像这样:
清单 6.18。拒绝重复电子邮件地址的测试。 (*spec/models/user_spec.rb*)
require 'spec_helper'
describe User do
before do
@user = User.new(name: "Example User", email: "user@example.com")
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 验证器是否使用当前数据来验证用户实例,即使它们只是存储在内存中并且当前没有尝试添加到数据库中?
【问题讨论】:
-
为什么大家突然开始在 rspec 中使用隐式接收者和主题?好的 ole
it "does something"和显式变量有什么问题?就是吐槽。无法弄清楚你的测试对象是谁?新用户?还是缺少一些代码?顺便说一句,我会定期与Active Record Validations and Callbacks联系,这可能对您有所帮助。 -
@ArtShayderov,作者没有提供这段代码:
subject { @user }。您可以点击他的链接亲自查看。 -
你说得对,如果代码丢失了。对不起;)
标签: ruby-on-rails