RSpec测试非验证has_many通过关系

时间:2012-01-05 01:25:52

标签: ruby-on-rails-3 rspec rspec2

我的文件之间有很多关系。

说我有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它适当地未通过验证,但我不知道如何为此编写测试。

有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

将其添加到集合

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

然后确保它不在那里。