2017-06-20 6 views
2

Employeeモデルのdate_of_birth attrの独自の検証を作成しようとしていますが、私は何が間違っているのか見当たりません。私は本当に鼻の下で本当に奇妙なものだと確信しています。コードは以下の通りで、私のエラーメッセージは次のとおりです。なぜnil:model.rb内でこのself.attributeにアクセスしようとするとNilClassエラーが発生しますか?

NoMethodError: 
    undefined method `<' for nil:NilClass 

employee.rb

class Employee < ApplicationRecord 
    belongs_to :quote 

    validates_presence_of :first_name, :last_name, :email, :gender, :date_of_birth, :salary 
    validates :first_name, length: { minimum: 2, message: "minimum of 2 chars" } 
    validates :last_name, length: { minimum: 2, message: "minimum of 2 chars" } 
    validates_email_format_of :email, :message => 'incorrect email format' 
    validate :older_than_16 

    enum gender: [ :m, :f ] 

    private 

    def older_than_16 
     self.date_of_birth < Time.now-16.years 
    end 

end 

schema.rb

ActiveRecord::Schema.define(version: 20170620125346) do 

    # These are extensions that must be enabled in order to support this database 
    enable_extension "plpgsql" 

    create_table "employees", force: :cascade do |t| 
    t.string "first_name" 
    t.string "last_name" 
    t.string "email" 
    t.string "initial" 
    t.integer "gender" 
    t.date  "date_of_birth" 
    t.integer "salary" 
    t.integer "quote_id" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.index ["quote_id"], name: "index_employees_on_quote_id", using: :btree 
    end 

employee_spec.rb

RSpec.describe Employee, type: :model do 
    describe 'validations' do 

     it { should validate_presence_of(:date_of_birth) } 
     it { should_not allow_value(Date.today-15.years).for(:date_of_birth) } 
     # it { should allow_value(Date.today-17.years).for(:date_of_birth) } 
    end 
end 

答えて

3

カスタムメソッドマッチングをしても最初のテストのために呼ばれたがself.date_of_birthれます実際には0123ですこのエラーが表示されます。
date_of_birthnilでないかどうかを確認してから比較してください。
モデルが無効であるとみなされる場合は、コレクションにadd a new entryとする必要があります。
今完璧に動作Aschen @

def older_than_16 
     return if self.date_of_birth.nil? 
     if self.date_of_birth > Time.now-16.years 
      errors.add(:date_of_birth, "Should be at least 16 years old") 
     end 
    end 
+0

おかげで、(また、あなたの状態をチェックし、私はあなたのテストパスを作成する代わりに<>を使用します)。しかし、私は 'self.date_of_birth'がどのようにこれまでに無かったのか分かりません。存在は検証され、テストに合格しましたか?どうしたの? – jbk

+0

私は 'should-matcher'が内部的にどのように動作するのかわかりませんが、'それはvalidate_presence_of(:date_of_birth)} '' nil'値を渡して存在確認をチェックしようとします。 modelは 'model.valid?'に対してfalseを返します。 – Aschen

関連する問題