Rails 密码验证在编写不相关的测试时失败



我正在做Michael Hartl的Rails教程,我在第14章

基本上,我正在构建一个Twitter克隆,以学习Rails。
在本章中,用户可以相互关注。

在编写第一个测试以检查这些关系后:

user_test.rb

test "should follow and unfollow a user" do
michael = users(:michael)
archer  = users(:archer)
assert_not michael.following?(archer) 
michael.follow(archer)                    # LINE OF THE ERROR (rb:100)
assert michael.following?(archer)
michael.unfollow(archer)
assert_not michael.following?(archer)
end

弹出此错误:

错误

ERROR["test_should_follow_and_unfollow_a_user", UserTest, .192215816000044]
test_should_follow_and_unfollow_a_user#UserTest (6.19s)
ActiveRecord::RecordInvalid:         
ActiveRecord::RecordInvalid: Validation failed: 
Password can't be blank,        
Password is too short (minimum is 6 characters)
app/models/user.rb:102:in `follow'
test/models/user_test.rb:100:in `block in <class:UserTest>'

这很奇怪,因为到目前为止验证工作正常,甚至有一些测试来检查它们的正确行为(如果我删除User模型上的validation,这些测试会正确触发,但test/models/user_test.rb中的错误消失了(

models/user.rb主管

class User < ApplicationRecord
has_many :microposts, dependent: :destroy
has_many :active_relationships,  class_name:    "Relationship",
foreign_key:   "follower_id",
dependent:     :destroy
has_many :following,  through:   :active_relationships,
source:    :followed
attr_accessor :remember_token, :activation_token, :reset_token
before_save     :downcase_email
before_create :create_activation_digest
VALID_EMAIL_REGEX = /A[d+.a-z_-]+@[a-z]+.[a-z.]+z/i
validates(:name,     presence: true, length: { maximum: 50 } )
validates :email,    presence: true, length: { maximum: 255 }, 
format: { with: VALID_EMAIL_REGEX },                
uniqueness: { case_sensitive: false }
validates :password, presence: true, length: { minimum: 6 }
has_secure_password

触发错误的model/user.rb方法的方法

# follows a user
def follow(other_user)
following << other_user    # LINE OF THE ERROR (rb:102)
end

fixtures/users.yml主管

michael:
name:             Michael Example
email:            michael@example.com
password_digest:  <%= User.digest('password') %>
admin:            true
activated:        true
activated_at:     <%= Time.zone.now %>
archer:
name:             Sterling Archer
email:            duchess@example.gov
password_digest:  <%= User.digest('password') %>
activated:        true
activated_at:     <%= Time.zone.now %>

其他文件

所有其他文件都可以在我的GitHub页面上找到

我完成了相同的教程,在我的用户模型中,我验证了密码如下:

validates :password, presence: true, length: { minimum: 6 }, allow_nil: true

也许补充allow_nil:真的。

最新更新