编辑
使用问题的答案,我将测试更改为正确测试并通过的以下测试。
describe "when email is already taken" do
let(:user_with_same_email) { @user.dup }
before do
user_with_same_email.email.upcase!
user_with_same_email.save
end
it { user_with_same_email.should_not be_valid }
end
注意:不使用会使测试失败,因为如果它只是在块中重复,就像在这个问题的选择答案中let(:user_with_same_email) { @user.dup }
一样,它无法找到变量。user_with_same_email
before
我有一个User
模型和一个user_spec.rb
测试文件,它对User
模型属性进行了各种验证。
以前我在user_spec.rb
文件顶部写了以下内容来测试User
模型:
describe User do
before do
@user = User.new(name: "Example User", email: "user@example.com",
password: "foobar88", password_confirmation: "foobar88")
end
...
我想将此模型创建移动到,FactoryGirl
所以我创建了一个factories.rb
文件:
FactoryGirl.define do
factory :user do
name "foo"
email { "#{name}@example.com" }
password "foobar99"
password_confirmation "foobar99"
end
end
然后我改变了我的user_spec.rb
:
describe User do
before do
@user = FactoryGirl.create(:user)
end
...
现在每个测试都像以前一样通过,除了一个:
describe "when email is already taken" do
before do
user_with_same_email = @user.dup
user_with_same_email.email = @user.email.upcase
user_with_same_email.save
end
it { should_not be_valid }
end
现在,除非`FactoryGirl 跳过我的电子邮件唯一性验证,否则我无法弄清楚这里出了什么问题。
我的User
模型验证代码:
class User < ActiveRecord::Base
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i unless const_defined?(:VALID_EMAIL_REGEX)
has_secure_password
attr_accessible :name, :email, :password, :password_confirmation
has_many :programs
before_save { self.email.downcase! }
validates :name, presence: true, length: { maximum: 50 }
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }