我有简单的模型:
class Category < ActiveRecord::Base
belongs_to :board
validates :name, presence: true, uniqueness: {scope: :board_id}
validates :board, presence: true
validates :display_order, presence: true, uniqueness: {scope: :board_id}
before_save :set_display_order
private
def set_display_order
last = self.board.categories.order("display_order DESC").last
self.display_order = last.display_order + 100 if last
end
end
当我添加这个 before_save 回调时,这些测试开始失败:
it { should validate_uniqueness_of(:display_order).scoped_to(:board_id) }
it { should validate_uniqueness_of(:name).scoped_to(:board_id) }
有错误(如果私有方法中的行last = ...
):
NoMethodError:
undefined method `categories' for nil:NilClass
其他应该测试工作正常:
it { should validate_presence_of(:name) }
it { should validate_presence_of(:board) }
it { should belong_to :board }
知道这里有什么问题吗?我试图改变before_save
,before_validation
但还是一样。