Rspec valid_password 的 Devise 模型自定义验证失败?

Rspec fails for Devise model custom validation for valid_password?

我正在使用设计 gem(身份验证)。我正在为重置密码实施自定义验证。用户无法使用现有密码重置新密码。 在用户模型代码是:

 class User < ActiveRecord::Base
     include ActiveModel::ForbiddenAttributesProtection
     validate  :check_existed_password                               

      def check_existed_password
        if User.find_by_email(self.email).valid_password?(password)
          errors.add(:password, "password already existed, try other")
        end
      end
    end                               

在 运行 rspec 之后,出现错误:Failure/Error:no_email_user.should_not be_valid 没有方法错误: 未定义的方法`valid_password?'对于 nil:NilClass。 user_spec.rb 文件中所有预先存在的测试用例都失败了。有什么建议吗?

Blockquote

要么 email 不存在,要么您提供的 email 没有任何关联的用户。这就是您收到错误的原因。正如您正在检查的规范中那样,no_email_user.should_not be_valid 意味着没有电子邮件的用户应该是无效的。您添加的验证 check_existed_password 只需要 运行 update 而不是创建。所以将其设为:

validate  :check_existed_password, :on => :update

因为用户将在更新操作而不是创建时重置密码。 目前它会尝试查找尚未创建的用户并每次都抛出错误。

希望这对您有所帮助。