2012-01-05 73 views
1

我在文檔之間有多對多的關係。通過關係RSpec測試不驗證has_many

說我有document1document2。我有許多桌子,那裏有父母和孩子。

document.rb

has_many :child_relationships, :class_name => "DocumentRelationship", :foreign_key => "child_id", :dependent => :destroy 
    has_many :parents, :through => :child_relationships, :source => :parent 

    has_many :parent_relationships, :class_name => "DocumentRelationship", :foreign_key => "parent_id", :dependent => :destroy 
    has_many :children, :through => :parent_relationships, :source => :child 

document_relationship.rb

belongs_to :parent, :class_name => "Document", :foreign_key => "parent_id" 
    belongs_to :child, :class_name => "Document", :foreign_key => "child_id" 

    validates_uniqueness_of :child_id, :scope => [:parent_id] 

    validates_presence_of :parent_id 
    validates_presence_of :child_id 
    validate :obeys_chronology 

    def obeys_chronology 
    errors.add(:child_id, "must be created after its parent") if child_id.to_i < parent_id.to_i 
    errors.add(:child_id, "cannot be its own parent") if child_id.to_i == parent_id.to_i 
    end 

如果我說document2.children << document1它適當地驗證失敗,但我不知道怎麼寫一個測試此。

有沒有更好的方法來做到這一點?

回答

0

將它添加到集合

document2.children << document1 
document2.children.contain?(document1).should == false 

然後確保它不是在那裏。

+0

我剛剛試過。 失敗/錯誤:d2.children << d1 ActiveRecord :: RecordInvalid: 驗證失敗:必須在其父代後創建子代 #./spec/models/document_spec.rb:65:in'block(3 levels)in ' – Cyrus 2012-01-05 02:09:38