1
這裏是我的型號代碼:Rails的模型失敗的測試斷言
class User < ActiveRecord::Base
validates :email, :presence => true,
:uniqueness => true,
:format => {
:with => %r{^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$},
:message => "You must enter a valid email address."
}
validates :password, :presence => true,
:confirmation => true,
:length => { :in => 6..20 }
validates :password_confirmation, :presence => true
validates :firstname, :presence => true
validates :lastname, :presence => true
end
而且我的測試:
require 'test_helper'
class UserTest < ActiveSupport::TestCase
test "user email must not be empty" do
user = User.new
assert user.invalid?
assert user.errors[:email].any?
end
test "user password must be between 6 and 20 characters" do
user = User.new(:email => "[email protected]",
:firstname => "sergio",
:lastname => "tapia")
user.password = "123"
assert user.invalid?
user.password = ""
assert user.invalid?
#6 characters.
user.password = "123456"
assert user.valid?
#20 characters.
user.password = "123456789"
assert user.valid?
#21 characters.
user.password = "123456789"
assert user.invalid?
end
end
而測試的結果:
[email protected]:~/code/ManjarDeOro$ rake test:units
Run options:
# Running tests:
.F
Finished tests in 0.105599s, 18.9395 tests/s, 47.3488 assertions/s.
1) Failure:
test_user_password_must_be_between_6_and_20_characters(UserTest) [/home/sergio/code/ManjarDeOro/test/unit/user_test.rb:24]:
Failed assertion, no message given.
2 tests, 5 assertions, 1 failures, 0 errors, 0 skips
因此斷言失敗上此位:
#6 characters.
user.password = "123456"
assert user.valid?
那麼發生了什麼?我對斷言的條件是否有誤?我認爲一個6字符的密碼會將我的「用戶」對象變成.valid。
我是新來的Rails。
您忘記添加'password_confirmation =「123456」'使用戶有效 – yoavmatchulsky 2012-02-03 16:26:25
謝謝,我錯過了。 – 2012-02-03 16:33:20
@yoavmatchulsky應該添加作爲答案。 – tadman 2012-02-03 16:36:37