【问题标题】:Why is my rspec test failing for user confirmation?为什么我的 rspec 测试未通过用户确认?
【发布时间】:2013-01-20 11:37:33
【问题描述】:

这是失败的测试:

context "when password does not match confirmation" do
  before { build(:user, :password_confirmation => 'mismatch') }
  it { should_not be_valid }
end

我在这个测试套件中使用 Factory Girl 的 build 方法。

我的用户模型:

class User < ActiveRecord::Base
  attr_accessible :email, :name, :password, :password_confirmation
  has_secure_password

  validates :password_confirmation, presence: true
  validates :password, presence: true, length: { minimum: 5 }
end

更新:在使用 has_secure_password 时,您不需要使用 :confirmation => true 标记 :password 字段。处理好了:见源码:https://github.com/rails/rails/blob/master/activemodel/lib/active_model/secure_password.rb

验证工作正常 - 当我尝试在控制台创建新用户时收到正确的错误消息。那么为什么测试失败了呢?错误在哪里?

【问题讨论】:

    标签: ruby-on-rails-3 authentication rspec


    【解决方案1】:

    验证不能正常工作,您没有验证password_confirmation 是否与password 匹配。请参阅http://guides.rubyonrails.org/active_record_validations_callbacks.html#confirmation 了解更多信息。

    此外,您需要确保您实际测试的是您想要测试的内容 - 您的这些测试的主题是 build(:user),而它需要是 build(:user, password_confirmation: 'mismatch')。将上述代码中的before 更改为subject,以正确设置测试主题。

    【讨论】:

    • 那么我应该把:confirmation =&gt; true放在哪里?
    • 如指南所述,在您要验证确认的任何字段的验证中。
    • 更新了上面的代码,它仍然无法正常工作 - 测试一直失败
    • 你的考试题目是什么?
    • 也就是说,不是您正在使用不匹配的密码确认建立的用户? ;)
    猜你喜欢
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    相关资源
    最近更新 更多