【问题标题】:Factory Girl failing presence validation工厂女孩未通过存在验证
【发布时间】:2017-07-17 20:13:19
【问题描述】:

我有以下任务模型:

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

及以下FactoryGirl对象创建代码:

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 创建的任务对象中缺少字段“完成”:

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

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

这里发生了什么?我正确设置了完整的属性,并且身体检查正常。这里也是任务架构:

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

【问题讨论】:

    标签: ruby-on-rails factory-bot


    【解决方案1】:

    在 ruby​​ 中,false 被视为空白(不存在)值(与nil、空字符串/数组和其他空白值一起)。因此,存在验证器正确地拒绝了该记录。

    documentation 有以下评论:

    如果您想验证布尔字段是否存在(其中实际值为truefalse),您将需要使用validates_inclusion_of :field_name, in: [true, false]

    这是由于Object#blank? 处理布尔值的方式:false.blank? # =&gt; true

    【讨论】:

      猜你喜欢
      • 2012-01-03
      • 1970-01-01
      • 1970-01-01
      • 2012-03-08
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多