FactoryGirl:将 false 值分配给布尔值

FactoryGirl: Assigning a value of false to a boolean

在我的工厂中,我有一个布尔字段(已评估),我试图将其设置为 false。我希望该字段是必需的,并且始终设置为 truefalse

型号

  validates_presence_of :evaluated

工厂

FactoryGirl.define do
  factory :submission do
    evaluated true
    score 1.5
    ranking 1.5
    submission_type "user"
    .
    .
  end
end

测试中

    it { should validate_presence_of(:evaluated) }

当我运行它

     Failure/Error: expect(@submission).to be_valid
   expected #<Submission id: nil, competition_id: 163, user_id: 134, team_id: nil, evaluated: false, score: 1.5, ranking: 1.5, submission_type_cd: "user", withdrawn: true, withdrawn_date: "2016-02-08", created_at: nil, updated_at: nil> to be valid, but got errors: Evaluated can't be blank

如果我将值更改为 true,则测试通过

    evaluated true

如何为布尔值设置错误值的工厂?

我宁愿使用 inclusion_of 验证而不是 presence 验证。

来自railsdoc,

如果您想验证布尔字段的存在(其中的真实值为真和假),您需要使用

validates_inclusion_of :field_name, in: [true, false]

这是由于 Object#blank? 处理布尔值的方式

false.blank? # => true

然后你的测试会是这样的,

it { should ensure_inclusion_of(:field_name).in_array([true, false]) }