我有簡單的模型:早該和before_回調
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
,但仍然相同。