rails 5验证程序在模型创建期间无法保护缺少属性?

时间:2017-08-25 05:18:51

标签: ruby-on-rails

似乎无法使我的验证器工作以确保存在所有属性以允许创建用户。具有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 本

1 个答案:

答案 0 :(得分:1)

问题是有两种方法createcreate!。第一个是create

  

无论对象是否已成功保存到数据库

,都会返回结果对象

create!

  

如果验证失败,则引发RecordInvalid错误,与Base #crera

不同

因此,create无声地失败并且不会引发任何异常,但您仍然可以检查该实例,看到它是新记录并且有错误等,{{1}通过提出你期望它提出的错误来吵闹。简而言之,您的测试应该是:

create!