首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RSpec忽略attr_accessor?

RSpec忽略attr_accessor?
EN

Stack Overflow用户
提问于 2011-03-04 23:39:20
回答 1查看 1.7K关注 0票数 0

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

代码语言:javascript
复制
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

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

代码语言:javascript
复制
@user.updating_password = true
if @user.update_attributes(params[:user]) ...

因此,我将验证标记为在密码上运行。在开发模式下,这很有效-如果用户尝试输入太短或太长的密码,模型将无法通过验证。我的问题是,在我的生命中,我不能让我的测试通过。以下是我的规范:

代码语言:javascript
复制
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

当我运行这些测试时,我总是得到这样的错误:

代码语言:javascript
复制
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而验证密码吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-03-05 00:24:47

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

我认为这是有意义的,因为当验证失败时,通常会再次显示带有错误消息的表单和填充了传入的坏值的输入。在Rails应用程序中,这些值通常来自有问题的模型对象。如果错误的值没有保存到模型中,它们将丢失,并且您的表单将指示旧的“好”值未通过验证。

不执行此检查:

代码语言:javascript
复制
@user.password.should == old_password

也许可以试试:

代码语言:javascript
复制
@user.errors[:password].should_not == nil

或者其他一些有意义的测试。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5195893

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档