Rails 在编写不相关的测试时,密码验证莫名其妙地失败了

Rails password validation fails misteriously while writing unrelated tests

我正在做 Michael Hartl 的 Rails 教程,我在 chapter 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 %>

其他文件

可以找到所有其他文件on my github page

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

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

也许添加 allow_nil:正确。