Factory Girl 存在验证失败

Factory Girl failing presence validation

我有以下任务模型:

class Task < ApplicationRecord
  validates :body, presence: true, length: { minimum: 10 }
  validates :complete, presence: true
end

以及以下 FactoryGirl object 创建代码:

FactoryGirl.define do
  factory :incomplete_task, class: :Task do
    body { Faker::Pokemon.name + Faker::Pokemon.name }
    complete false

    factory :complete_task do
      complete true
    end
  end
end

在我的任务控制器测试中,我有:

  describe '#update' do
    it 'toggles completion' do
      incomplete_task = create :incomplete_task
      toggle_completion(incomplete_task)
      expect(incomplete_task.complete).to be_true
    end
  end

但是,这失败了,因为 FG 创建的任务 object 中缺少字段 'complete':

Failures:
  1) TasksController#update toggles completion
     Failure/Error: incomplete_task = create :incomplete_task

     ActiveRecord::RecordInvalid:
       Validation failed: Complete can't be blank

这是怎么回事?我正确设置了 complete 属性,并且 body 检查正常。这也是任务架构:

# Table name: tasks
#
#  id         :integer          not null, primary key
#  created_at :datetime         not null
#  updated_at :datetime         not null
#  body       :text
#  complete   :boolean

在 ruby 中,false 被视为空白(不存在)值(以及 nil、空 string/array 和其他空白值)。因此,存在验证器正确地拒绝了该记录。

documentation 有以下评论:

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.