1
我有一个字符串列在我的数据库中,包含一个时区。有效值包括nil
或任何的ActiveSupport识别为一个时区为什么我必须明确地剔除shoulda匹配器包含的空白:`验证通过?
我用早该-的匹配写规格为我的模型验证:
# app/models/my_model.rb
class MyModel < ApplicationRecord
validates :timezone, inclusion: ActiveSupport::TimeZone::MAPPING.keys, allow_nil: true
end
# spec/models/my_model_spec.rb
describe "timezone" do
it do
should validate_inclusion_of(:timezone).
in_array(ActiveSupport::TimeZone::MAPPING.keys).
allow_blank
end
end
它扔了一个错误:
Failure/Error: it { should validate_inclusion_of(:timezone).in_array(ActiveSupport::TimeZone::MAPPING.keys).allow_blank }
MyModel did not properly validate that
:timezone is either ‹"International Date Line West"›, ‹"Midway Island"›,
‹"American Samoa"›, ‹"Hawaii"›, ‹"Alaska"›, ‹"Pacific Time (US &
.....
.....
.....
‹"Auckland"›, ‹"Wellington"›, ‹"Nuku'alofa"›, ‹"Tokelau Is."›, ‹"Chatham
Is."›, or ‹"Samoa"›, but only if it is not blank.
After setting :timezone to ‹""›, the matcher expected the
MyModel to be valid, but it was invalid
instead, producing these validation errors:
* timezone: ["is not included in the list"]
早该的匹配将列设置为""
,并期望验证通过。但为什么会这样呢? nil
是严格允许的,但空白字符串值不应该是正确的?
有没有更适当的方法来设置,我已经错过了?
要解决它,我使用我们的before_validation
块。 (而且我知道nilify_blanks gem可以做同样的事情)。但感觉奇怪的是,我必须包括所有
before_validation do
self[:timezone] = nil if self[:timezone].blank?
end