似乎無法讓我的驗證器工作以確保所有屬性都存在以允許創建用戶。具有2個屬性的基本用戶rails 5驗證器在模型創建過程中沒有針對缺少的屬性進行保護?
class User < ApplicationRecord
validates :name, presence: true
validates :email, presence: true
end
測試在創建時檢查名稱和電子郵件是否存在。這些#pass
RSpec.describe User, type: :model do
context 'validations' do
subject { FactoryGirl.build(:user) }
it { is_expected.to validate_presence_of(:email) }
it { is_expected.to validate_presence_of(:name) }
it "fails to create user unless both are present" do
expect { User.create(:name => 'jo bloggs1', :noemail => '[email protected]')}.to raise_error(ActiveModel::UnknownAttributeError)
end
end
end
,但如果我試着和丟失屬性不會引發錯誤
it "fails to create user unless both are present" do
expect { User.create(:name => 'jo bloggs1')}.to raise_error(ActiveModel::MissingAttributeError)
end
結果創建模型
1) User validations fails to create user unless both are present
Failure/Error: expect { User.create(:name => 'jo bloggs1')}.to raise_error(ActiveModel::MissingAttributeError)
expected ActiveModel::MissingAttributeError but nothing was raised
# ./spec/models/user_spec.rb:12:in `block (3 levels) in <top (required)>'
僅供參考,FactoryGirl
FactoryGirl.define do
factory :user do
name "MyString"
email "MyString"
end
end
我試圖巧妙的東西一樣
class User < ApplicationRecord
# before_create :run_it
after_initialize :all_present?
validates :name, presence: true
validates :email, presence: true
private
def all_present?
if (@email.nil? || @name.nil?)
raise ActiveModel::MissingAttributeError.new()
end
end
end
,但似乎無法手動提出這些...? 我做錯了什麼? tx全部 本
拿上這個一讀:http://api.rubyonrails.org/classes/ActiveModel/MissingAttributeError.html – vee
...這:HTTP:// WWW。 rubydoc.info/docs/rails/4.1.7/ActiveRecord/Validations/PresenceValidator – vee