2017-05-29 3 views
1

タイムゾーンを保持するデータベースに文字列があります。有効な値はnilまたはactivesupportのは、私は私のモデル検証のための仕様を作成するためにshoulda-マッチャを使用するタイムゾーンなぜshoulda matcherの `inclusion:`検証が成功するために、明示的に空白をnilifyする必要がありますか?

として認識して何かを含める:

# 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"] 

Shouldaマッチャーを列を""に設定し、検証が成功するはずです。しかし、それはなぜ期待されていますか? nilは厳密に許可されますが、空白の文字列値は正しくはありませんか?

これを設定するより適切な方法がありますか?

この問題を回避するには、before_validationブロックを使用します。 (そして私は同じことをするnilify_blanks宝石を知っています)。しかし、それは私がすべての

before_validation do 
    self[:timezone] = nil if self[:timezone].blank? 
end 

答えて

2

.blank?nilfalseとよりimporantly ""(空の文字列)のためにtrueを返すactivesupportの方法であることを含める必要があるだろうことを奇妙に感じています。

なぜallow_blankは空の文字列でテストされますか?代わりにallow_nilを使用してください。

# spec/models/my_model_spec.rb 
describe "timezone" do 
    it do 
    should validate_inclusion_of(:timezone). 
     in_array(ActiveSupport::TimeZone::MAPPING.keys). 
     allow_nil 
    end 
end 
関連する問題