Oct 22
2008

Test destruction of your Rails associations

Here's a handy test helper I wrote this afternoon during some Cashboard testing.

It ensures that all associations are destroyed that you specify. Great for those ":dependent => :destroy" calls.

def assert_associations_destroyed(item, associations=[])
  ids = {}
  associations.each do |assoc|
    ids[assoc] = eval("item.#{assoc}.find(:all, :select => 'id')")
  end
  ids.each do |key, things|
    assert things.size > 0, "#{key} doesn't have more than 1 item."
  end
  
  item.destroy
  
  ids.each do |key, things|
    assert_equal 0, key.to_s.classify.constantize.find(
      :all, 
      :conditions => ["id IN (?)", things.collect { |thing| thing.id }]
    ).size
  end
end
Written by Seth Banks

Seth spends most of his days leading the design team at Green Bits and improving Cashboard. Occasionally he finds time to write about music, design, startups, and technology.

Tagged: rails, testing, tdd