似乎无法使我的验证器工作以确保存在所有属性以允许创建用户。具有2个属性的基本用户
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 => 'c@c.co')}.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)>'
fyi,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 all 本