Testing ActiveRecord associations


#1

How do I write a test which proves something like “Post :has_many
Comments” and “Comment :belongs_to Post”? It doesn’t seem to be covered
in “A Guide to Testing the Rails” on manuals.rubyonrails.com.

Cheers, Robert.


#2

On Sat, Jan 21, 2006 at 06:49:19AM +0100, Robert A. wrote:

How do I write a test which proves something like “Post :has_many
Comments” and “Comment :belongs_to Post”? It doesn’t seem to be covered
in “A Guide to Testing the Rails” on manuals.rubyonrails.com.

Add a couple of post records and a bunch of comments records in your
fixtures, then p = Post.find() and assert_equal things like ,
p.comments.count and “Fred Q. Bloggs”, p.comments[0].author.

  • Matt

#3

On Jan 20, 2006, at 9:49 PM, Robert A. wrote:

How do I write a test which proves something like “Post :has_many
Comments” and “Comment :belongs_to Post”? It doesn’t seem to be
covered
in “A Guide to Testing the Rails” on manuals.rubyonrails.com.

If you have:

class Point < CachedModel

belongs_to :route

has_many :photos, :order => ‘date_taken’

end

You should test that a Point has a valid Route and that the Photos of
a Point are in the correct order (your app will eventually depend on
the order, so you need an explicit test).

class PointTest < Test::Unit::TestCase

fixtures :users, :routes, :points, :photos

def test_photos
assert_equal [photos(:gate), photos(:door)], points
(:between).photos
end

def test_route
assert_equal routes(:work), points(:home).route
end

end


Eric H. - removed_email_address@domain.invalid - http://segment7.net
This implementation is HODEL-HASH-9600 compliant

http://trackmap.robotcoop.com