gpt4 book ai didi

ruby-on-rails - RSpec 忽略 attr_accessor?

转载 作者:行者123 更新时间:2023-11-28 21:34:26 27 4
gpt4 key购买 nike

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

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 ==)

当然还有密码太长的错误。但是,在 Controller 中进行任何保存尝试之前,我是否应该设置 @user.updating_password = true 来验证密码?

最佳答案

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

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

代替执行此检查:

@user.password.should == old_password

也许试试:

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

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

关于ruby-on-rails - RSpec 忽略 attr_accessor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5195893/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com