2

我的验证确保必填字段只能设置为AR

在模型中:

validates :status_code, inclusion: { in: %w(A R) }

在 RSpec 中,我有以下规范:

it { expect(@car).to allow_value("A", "R").for(:status_code) }
it { expect(@car).to_not allow_value(nil, "").for(:status_code) }

第一个 RSpec 通过,但第二个出现错误:

Failure/Error: it { expect(@car).to_not allow_value(nil, "").for(:status_code) }
       Expected errors  when status_code is set to "", got no errors

我错过了什么?我正在使用 RSpec 3.1。

4

1 回答 1

2

Built-in validators accept the boolean options :allow_blank and :allow_nil to control how it should behave when the value is one of those two. Try this:

validates :status_code, inclusion: { in: %w(A R), allow_blank: false, allow_nil: false }

It'd probably also work to add a presence validator to handle nil and the empty string:

validates :status_code, inclusion: { in: %w(A R) }, presence: true
于 2014-09-25T14:02:46.510 回答