2013-10-16 1 views
3

나는 간단한 모델을 가지고 : 나는이 before_save 콜백을 추가진작 및 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 

, 이러한 테스트가 실패하기 시작 : 오류

it { should validate_uniqueness_of(:display_order).scoped_to(:board_id) } 
    it { should validate_uniqueness_of(:name).scoped_to(:board_id) } 

(이 private 메소드의 라인 경우 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_savebefore_validation에 여전히 동일한을 변경했습니다.

답변

2

했어야가 DB에 레코드를 작성하기 때문에. 보석은 기록 건너 뛰는 검증 category 그것이 category.board # => nil을 의미하고 무기 호에서 방법 categories를 호출 비어 만들어 귀하의 경우에는 http://rubydoc.info/github/thoughtbot/shoulda-matchers/master/Shoulda/Matchers/ActiveModel#validate_uniqueness_of-instance_method Ensures that the model is invalid if the given attribute is not unique. It uses the first existing record or creates a new one if no record exists in the database. It simply uses ':validate => false' to get around validations, so it will probably fail if there are 'NOT NULL' constraints. In that case, you must create a record before calling 'validate_uniqueness_of'.

을 만듭니다.

당신은 고유성에 대한 시험에 대한 레코드를 직접 만들어야합니다. shoulda_matchers 및 AR 콜백이 문제를 해결

0

한가지 방법을 사용 했어야 정합 시험 대상을 재정의한다.

예 :

# category_spec.rb 

# assuming you're using factorygirl and have this setup correctly 
let(:board) { FactoryGirl.create(:board, :with_many_categories) } 
subject { FactoryGirl.build(:category, board: board) } 

# your shoulda matcher validations here