Forum: Ruby on Rails Testing ActiveRecord associations

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Af7b9309245ba5074480481dc4eed114?d=identicon&s=25 Robert Atkins (ratkins)
on 2006-01-21 06:49
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.
55428cbf149e35dd4b65f1d019d04139?d=identicon&s=25 Matthew Palmer (Guest)
on 2006-01-21 08:02
(Received via mailing list)
On Sat, Jan 21, 2006 at 06:49:19AM +0100, Robert Atkins 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(<id>) and assert_equal things like <n>,
p.comments.count and "Fred Q. Bloggs", p.comments[0].author.

- Matt
58479f76374a3ba3c69b9804163f39f4?d=identicon&s=25 Eric Hodel (Guest)
on 2006-01-21 22:59
(Received via mailing list)
On Jan 20, 2006, at 9:49 PM, Robert Atkins 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 Hodel - drbrain@segment7.net - http://segment7.net
This implementation is HODEL-HASH-9600 compliant

http://trackmap.robotcoop.com
This topic is locked and can not be replied to.