【问题标题】:Rspec validation failed - attribute can't be blank but it isn't blankRspec 验证失败 - 属性不能为空,但不能为空
【发布时间】:2011-10-15 22:46:34
【问题描述】:

我刚刚编写了一个测试来测试新用户创建是否还包含管理员设置。这是测试:

describe User do

  before(:each) do
    @attr = { 
      :name => "Example User", 
      :email => "user@example.com",
      :admin => "f"
    }
  end

  it "should create a new instance given valid attributes" do
    User.create!(@attr)
  end

  it "should require a name" do
    no_name_user = User.new(@attr.merge(:name => ""))
    no_name_user.should_not be_valid
  end

  it "should require an email" do
    no_email_user = User.new(@attr.merge(:email => ""))
    no_email_user.should_not be_valid
  end

  it "should require an admin setting" do
    no_admin_user = User.new(@attr.merge(:admin => ""))
    no_admin_user.should_not be_valid
  end

end

然后,在我的用户模型中,我有:

class User < ActiveRecord::Base
  attr_accessible :name, :email, :admin

  has_many :ownerships
  has_many :projects, :through => :ownerships

  email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  validates :name, :presence => true,
                   :length => { :maximum => 50 }

  validates :email, :presence => true,
                    :format => { :with => email_regex },
                    :uniqueness => { :case_sensitive => false }

  validates :admin, :presence => true

end

我清楚地创建了一个具有管理员设置的新用户,为什么它说它是假的?我将管理员设置的迁移创建为 admin:boolean。我是不是做错了什么?

这是错误:

Failures:

  1) User should create a new instance given valid attributes
     Failure/Error: User.create!(@attr)
     ActiveRecord::RecordInvalid:
       Validation failed: Admin can't be blank
     # ./spec/models/user_spec.rb:14:in `block (2 levels) in <top (required)>'

奇怪的是,当我注释掉 validates :admin, :presence => true 时,测试会正确创建用户,但在“用户应该需要管理员设置”时失败

编辑:当我将@attr :admin 值更改为“t”时,它起作用了!为什么值为false时不起作用?

【问题讨论】:

  • 失败:1) 用户应该在给定有效属性的情况下创建一个新实例失败/错误:User.create!(@attr) ActiveRecord::RecordInvalid: 验证失败:管理员不能为空# ./ spec/models/user_spec.rb:14:in `block (2 levels) in '

标签: ruby-on-rails rspec


【解决方案1】:

来自rails guides

因为 false.blank?是真的,如果你想验证一个 您应该使用的布尔字段验证 :field_name, :inclusion => { :in => [true, false] }.

基本上,看起来 ActiveRecord 在验证之前将您的“f”转换为 false,然后运行 ​​false.blank? 并返回 true(意味着该字段不存在),导致验证失败.因此,要在您的情况下修复它,请更改您的验证:

validates :admin, :inclusion => { :in => [true, false] }

对我来说似乎有点 hacky...希望 Rails 开发人员在未来的版本中重新考虑这一点。

【讨论】:

    猜你喜欢
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    相关资源
    最近更新 更多