Rails模型失败的测试断言

时间:2012-02-03 16:19:50

标签: ruby-on-rails ruby unit-testing model

这是我的模型代码:

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 => "stapia.gutierrez@gmail.com",
                    :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 = "12345678901234567890"
    assert user.valid?

    #21 characters.
    user.password = "123456789012345678901"
    assert user.invalid?

  end

end

测试结果:

sergio@sergio-VirtualBox:~/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的新手。

1 个答案:

答案 0 :(得分:4)

您的用户未通过验证,因为您错过了用户的password_confirmation部分。

user.password = "123456"
user.password_confirmation = "123456"
assert user.valid?