Rspec验证失败 - 属性不能为空,但不是空白

Mat*_*man 10 rspec ruby-on-rails

我刚刚编写了一个测试,用于测试新用户创建是否也包含管理设置.这是测试:

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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

我清楚地创建了一个具有管理员设置的新用户,为什么它说这是假的?我为admin设置创建了迁移: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)>'
Run Code Online (Sandbox Code Playgroud)

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

编辑:当我将@attr:admin值更改为"t"时,它可以工作!当值为false时,为什么它不起作用?

bri*_*ker 26

导轨指南:

自从false.blank?是的,如果你想验证布尔字段的存在,你应该使用validates:field_name,:inclusion => {:in => [true,false]}.

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

validates :admin, :inclusion => { :in => [true, false] }
Run Code Online (Sandbox Code Playgroud)

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