简体   繁体   中英

How can I test belongs_to, has_one, or has_many associations with test::unit?

I'm pretty new to rails testing and I tried using shoulda but it breaks whatever model I put it in so I figured I should just test them manually.

So my question to you oh great experts of SO is this:

How can I use test::unit to test that a model is associated with another model?

well, the most obvious solution would be something like this:

user = User.create(name: 'User')
2.times { user.friends.create(name: 'Other User') }

assert_equal(2, user.friends.count, "Unexpected associated records count")

but this is basically more like testing rails itself, you should not bother with that.

I would just check if user.respond_to?(:friends) . But, of course, it will fail if someone defines a method with that name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM