我剛寫了一個測試用於測試新用戶創建是否也包含管理設置。下面是測試:Rspec驗證失敗 - 屬性不能爲空,但它不是空白
describe User do
before(:each) do
@attr = {
:name => "Example User",
:email => "[email protected]",
: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+\-.][email protected][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
我清楚地創建了管理員設置的新用戶,那麼爲什麼說這是假的?我以管理員身份爲管理員設置創建了遷移:布爾值。我做錯什麼了嗎?
這裏的錯誤:
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)>'
奇怪的是,當我註釋掉只會驗證:管理員,:存在=> true,則測試正確創建的用戶,但失敗的「用戶應該要求管理員設置」
編輯:當我將@attr:admin值更改爲「t」時,它的工作原理!爲什麼當這個值是錯誤時它不工作?
實際的錯誤會有所幫助。 – bricker
失敗: 1)用戶應建立有效給出一個新的實例屬性 故障/錯誤:User.create(@ attr)使用 的ActiveRecord :: RecordInvalid: 驗證失敗:管理員不能爲空 #./spec /models/user_spec.rb:14:in'block(2 levels)in' –