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
感謝@ Aschen,現在完美的作品。但我不明白「self.date_of_birth」是如何從零開始的?存在被驗證並通過測試?它是如何零?感謝您在這裏幫助我 – jbk
我不知道'should-matcher'如何在內部工作,但我認爲'it {validate_presence_of(:date_of_birth)}'嘗試通過傳遞'nil'值來檢查存在驗證,除了模型將爲'model.valid?'返回false – Aschen