【问题标题】:Ruby On Rails testing User Model with RSpec - password and password_confirmation doesn't work properlyRuby On Rails 使用 RSpec 测试用户模型 - 密码和密码确认无法正常工作
【发布时间】:2018-08-07 13:47:24
【问题描述】:

这是我的第一篇文章。我开始学习 Ruby 和 Ruby On Rails 框架。

我想用 RSpec 测试用户模型,但我在验证 passwordpassword_confirmation 时遇到问题。

代码:https://github.com/paw3lgora/gCMS/blob/master/spec/models/user_spec.rb

我的线路有问题:it { should validate_confirmation_of(:password) }

我不想使用 BCrypt 的 devise gem 或 has_secure_password 方法,因为我学习 Ruby,我想从头开始实现我的身份验证系统并在未来添加 Argon2。

这给了我这样的错误:

1) 用户验证密码应验证 :password_confirmation 匹配 :password 失败/错误:它 { 应该 validate_confirmation_of(:password) }

   User did not properly validate that :password_confirmation matches
   :password.
     After setting :password_confirmation to ‹"some value"›, then setting
     :password to ‹"different value"›, the matcher expected the User to be
     invalid and to produce the validation error "doesn't match Password"
     on :password_confirmation. The record was indeed invalid, but it
     produced these validation errors instead:

     * name: ["Nazwa użytkownika nie może być pusta.", "Nazwa użytkownika
       jest za krótka. Minimum 2 znaki."]
     * email: ["Nie podałeś emaila.", "Email jest za krótki. Minimum 5
       znaków.", "Podałeś złą nazwę użytkownika."]
     * password_confirmation: ["Hasła nie pasują do siebie."]
 # ./spec/models/user_spec.rb:27:in `block (4 levels) in <top (required)>'

帮帮我! :)

【问题讨论】:

  • 如果你使用的是应该匹配器,你需要使用validate_confirmation_of(:password).with_message("Hasła nie pasują do siebie.")。默认情况下它仅适用于英语,因为期望基于错误消息的文本。
  • 非常感谢你!

标签: ruby-on-rails ruby testing rspec tdd


【解决方案1】:

如果你仔细阅读整封邮件,你会看到

记录确实无效,但是 而是产生了这些验证错误:

这意味着验证失败,但匹配器希望验证错误与指定的完全一致。还有更多。

你有两个选择:

  • 在您的规范中添加所有失败的验证预期
  • :name:email 有效的方式准备用户对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-08
    • 2018-10-24
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    相关资源
    最近更新 更多