gpt4 book ai didi

ruby-on-rails - 在编写不相关的测试时,Rails 密码验证错误地失败

转载 作者:行者123 更新时间:2023-11-28 21:23:55 25 4
gpt4 key购买 nike

我正在学习 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: true。

关于ruby-on-rails - 在编写不相关的测试时,Rails 密码验证错误地失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45718705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com