繁体   English   中英

RSpec忽略了attr_accessor?

[英]RSpec ignoring attr_accessor?

我建立了一个具有条件验证的User AR模型,该模型与条件验证中的Railscast情节几乎相同。 所以基本上我的用户模型是这样的:

class User < ActiveRecord::Base
  attr_accessor :password, :updating_password

   validates :password, :presence => true,
             :confirmation => true,
             :length => { :within => 6..40 },
             :if => :should_validate_password?

  def should_validate_password?
    updating_password || new_record?
  end
end

现在,在用户可以更改其密码的操作中,我有以下两行:

@user.updating_password = true
if @user.update_attributes(params[:user]) ...

这样我就标记了要在密码上运行的验证。 在开发模式下,这很有用-如果用户尝试输入太短或太长的密码,则该模型将无法通过验证。 我的问题是我一生无法通过测试。 这是我的规格:

require 'spec_helper'

 describe PasswordsController do
   render_views

   before(:each) do
     @user = Factory(:user)
   end

   describe "PUT 'update'" do

     describe "validations" do

     before(:each) do
       test_sign_in(@user)
     end

       it "should reject short passwords" do
         short = "short"
         old_password = @user.password
         @attr2 = { :password => short, :password_confirmation => short }
         put :update, :user_id => @user, :old_password => @user.password, :user => @attr2
         @user.password.should == old_password
       end

       it "should reject long passwords" do
         long = "a" * 41
         old_password = @user.password
         @attr2 = { :password => long, :password_confirmation => long }
         put :update, :user_id => @user, :old_password => @user.password, :user => @attr2
         @user.password.should == old_password
       end
      end
     end
    end

当我运行这些测试时,我总是会收到错误消息:

1) PasswordsController PUT 'update' validations should reject short passwords
 Failure/Error: @user.password.should == old_password2
   expected: "foobar"
        got: "short" (using ==)

当然,密码错误的时间太长。 但是,在控制器中进行任何保存尝试之前,是否应该通过设置@user.updating_password = true来验证密码?

我认为问题不在于代码,而在于您期望它做什么。 当您调用update_attributes并传递错误的值时,即使验证失败,该值也会保存到模型对象中。 错误值尚未推送到数据库。

我认为这是有道理的,因为当验证正常失败时,您将再次显示带有错误消息的表单,并使用传入的错误值填充输入。在Rails应用程序中,这些值通常来自所讨论的模型对象。 如果不良值未保存到模型中,则它们将丢失,并且您的表单将指示旧的“良好”值验证失败。

而不是执行此检查:

@user.password.should == old_password

也许尝试:

@user.errors[:password].should_not == nil

或其他有意义的测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM