gpt4 book ai didi

ruby-on-rails - false 在 rspec 中被认为是 nil 吗?

转载 作者:行者123 更新时间:2023-12-05 01:11:36 27 4
gpt4 key购买 nike

客户表中有事件的字段名称。它在 customer.rb 中验证如下:

validates :active, :presence => true

这是测试短名称字段的 rspec 代码:

it "should be OK with duplicate short_name in different active status" do
customer = Factory(:customer, :active => false, :short_name => "test user")
customer1 = Factory.build(:customer, :active => true, :short_name => "Test user")
customer1.should be_valid
end

short_name 的验证是:

  validates :short_name, :presence => true, :uniqueness => { :scope => :active }

以上代码导致的错误:

  1) Customer data integrity should be OK with duplicate short_name in different active status
Failure/Error: customer = Factory(:customer, :active => false, :short_name => "test user")
ActiveRecord::RecordInvalid:
Validation failed: Active can't be blank
# ./spec/models/customer_spec.rb:62:in `block (3 levels) in <top (required)>'

似乎分配给事件字段的错误值被 rspec 认为是空白或 nil,并且未通过数据验证检查。试图将 0 用作 false,但它会导致相同的错误。如果移除字段 active 的验证,则 rspec 案例通过。

最佳答案

这不是 rspec 问题,它与 Rails 的验证有关。我想您的 active 字段是一个 bool 值,引用 validates_presence_of 文档:

If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true

所以只需将您的验证器更改为类似以下内容(假设您想要“性感”语法),它应该可以工作:

validates :active, :inclusion => [true, false]

关于ruby-on-rails - false 在 rspec 中被认为是 nil 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8435127/

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