2017-08-25 21 views
-1

似乎無法讓我的驗證器工作以確保所有屬性都存在以允許創建用戶。具有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全部 本

+0

拿上這個一讀:http://api.rubyonrails.org/classes/ActiveModel/MissingAttributeError.html – vee

+0

...這:HTTP:// WWW。 rubydoc.info/docs/rails/4.1.7/ActiveRecord/Validations/PresenceValidator – vee

回答

1

問題是有2種方法,createcreate!。第一,create

最終的目標是返回的對象是否被成功保存到數據庫或不

而用create!

引發一個RecordInvalid錯誤,如果驗證失敗,不像Base#create

那麼,create默默地失敗並且不會引發任何異常,但是您仍然可以檢查該實例並查看它是否是新記錄,並且有錯誤等,並且通過提高您期望提升的錯誤來導致失敗。總之,您的測試應該是:

it "fails to create user unless both are present" do 
    expect { User.create!(:name => 'jo bloggs1')}.to raise_error(ActiveModel::MissingAttributeError) 
end 
+0

謝謝。當然。我有一些!只是不記得 – Ben

相關問題