我一直在创建一个基于Hartl课程的应用程序,并添加了组织的概念,其中有很多用户。这些测试是Hartl在指南第9.2节中建议的所有标准测试。由于将组织实施到应用程序中,其中一个测试用例在“已经采用电子邮件地址”时失败 - 这应该阻止用户两次注册相同的电子邮件地址。奇怪的是,这在应用程序本身中起作用(表单错误 - “用户电子邮件地址已被占用”)但不在我的测试中。你能帮忙说明为什么会破坏吗?
用户代码:
class User < ActiveRecord::Base
belongs_to :organization
#accepts_nested_attributes_for :organization
before_save { self.email = email.downcase }
before_create :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(?:\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
has_secure_password
validates :password, length: { minimum: 6 }
validates :organization, presence: true
组织代码:
class Organization < ActiveRecord::Base
validates :organization_name, presence: true, length: { maximum: 50 }, uniqueness: true
has_many :users, :inverse_of => :organization
accepts_nested_attributes_for :users
用户规范:
require 'spec_helper'
describe User do
before do
@user = FactoryGirl.create(:user)
end
subject { @user }
it { should respond_to(:name) }
it { should respond_to(:email) }
it { should respond_to(:password_digest) }
it { should respond_to(:password) }
it { should respond_to(:password_confirmation) }
it { should respond_to(:remember_token) }
it { should respond_to(:authenticate) }
it { should be_valid }
...
describe "when email address 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.define do
factory :organization do
organization_name "Example Org"
trait :wrong do
organization_name "Wrong Org"
end
trait :also_wrong do
organization_name "Another Wrong Org"
end
end
factory :user do
association :organization
name "Example Name"
email "email@example.com"
password "foobar"
password_confirmation "foobar"
trait :wrong_org do
association :organization, :factory => [:organization, :wrong]
end
trait :wrong_org2 do
association :organization, :factory => [:organization, :also_wrong]
end
end
end
从Rails控制台抛出的错误如下:
1)已经采用电子邮件地址的用户不应该有效 失败/错误:它{should_not be_valid} 期望
#<User id: 5287, name: "Example Name", email: "email@example.com", created_at: "2014-07-22 15:04:33", updated_at: "2014-07-22 15:04:33", password_digest: "$2a$04$jrxyuz9e574BoaAhZm6xkOUeAY5spyDut2CCEvAykMu...", organization_id: 5025, remember_token: "339dfafcac7bc5925dbf4e44f60a782f3bbbaa1b">.valid?
返回false,得到真实
我已经尝试更改测试中的代码,但无论我做什么都会导致错误。如上所述,当我在本地服务器中打开应用程序时,我可以使用所有功能,当我尝试使用重复的电子邮件地址注册时,它不会让我。我的测试代码出了什么问题?
答案 0 :(得分:0)
@user
完全有效:
@user
。这是有效的user_with_same_email
@user
具有相同的电子邮件user_with_same_email
返回false,但未在测试中检查正确的测试只是#dup
用户(或使用相同的电子邮件制作一个新的),然后检查 new 记录无效。