【发布时间】:2011-10-15 22:46:34
【问题描述】:
我刚刚编写了一个测试来测试新用户创建是否还包含管理员设置。这是测试:
describe User do
before(:each) do
@attr = {
:name => "Example User",
:email => "user@example.com",
:admin => "f"
}
end
it "should create a new instance given valid attributes" do
User.create!(@attr)
end
it "should require a name" do
no_name_user = User.new(@attr.merge(:name => ""))
no_name_user.should_not be_valid
end
it "should require an email" do
no_email_user = User.new(@attr.merge(:email => ""))
no_email_user.should_not be_valid
end
it "should require an admin setting" do
no_admin_user = User.new(@attr.merge(:admin => ""))
no_admin_user.should_not be_valid
end
end
然后,在我的用户模型中,我有:
class User < ActiveRecord::Base
attr_accessible :name, :email, :admin
has_many :ownerships
has_many :projects, :through => :ownerships
email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :name, :presence => true,
:length => { :maximum => 50 }
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false }
validates :admin, :presence => true
end
我清楚地创建了一个具有管理员设置的新用户,为什么它说它是假的?我将管理员设置的迁移创建为 admin:boolean。我是不是做错了什么?
这是错误:
Failures:
1) User should create a new instance given valid attributes
Failure/Error: User.create!(@attr)
ActiveRecord::RecordInvalid:
Validation failed: Admin can't be blank
# ./spec/models/user_spec.rb:14:in `block (2 levels) in <top (required)>'
奇怪的是,当我注释掉 validates :admin, :presence => true 时,测试会正确创建用户,但在“用户应该需要管理员设置”时失败
编辑:当我将@attr :admin 值更改为“t”时,它起作用了!为什么值为false时不起作用?
【问题讨论】:
-
失败:1) 用户应该在给定有效属性的情况下创建一个新实例失败/错误:User.create!(@attr) ActiveRecord::RecordInvalid: 验证失败:管理员不能为空# ./ spec/models/user_spec.rb:14:in `block (2 levels) in
'
标签: ruby-on-rails rspec