【发布时间】:2014-07-24 17:17:28
【问题描述】:
我一直在创建一个基于 Hartl 课程的应用程序,并添加了 Organization 的概念,其中 has_many 用户。这些测试是 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,得到 true
我尝试更改测试中的代码,但无论我做什么,它都会不断抛出错误。如上所述,当我在本地服务器中打开应用程序时,我可以使用所有功能,而当我尝试使用重复的电子邮件地址注册时,它不会让我这样做。我的测试代码有什么问题?
【问题讨论】:
-
@user仍然有效,并且永远有效。user_with_same_email无效。
标签: ruby-on-rails ruby rspec