2016-01-24 41 views
0

錯誤比方說,我有以下的驗證上Model.save操作來運行:檢查對象上model.save

def max_count 
    errors.add(:base, 'Cannot save more than 5 records') if self.class.active.count == 5 
    end 

爲什麼我Model.errors對象nil在救?

此帖可以作爲參考How to check for a database state before saving new records

+0

你使用什麼測試框架? –

+0

使用rspect但我用binding.pry()來檢查對象,並沒有看到名稱錯誤的任何屬性 – eugenekgn

回答

1

如果使用binding.pry你應該首先運行

object.valid? # it will load it's errors, if any 

,然後你可以看到它的錯誤與

object.errors 

首先,種子用5名is_active對象測試數據庫,然後寫測試:

it 'has error when creating sixth object' do 
    obj = Model.new(name: 'Name', is_active: true) 
    obj.valid? 
    expect(obj.errors[:base]).to eq 'Cannot save more than 5 records' 
end 
+0

是否建立了運行object.valid的做法?在運行.save之前的object.save之前? – eugenekgn

+0

是的,否則錯誤將不會被加載,'obj.errors'將不會返回任何內容 –