簡體   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