简体   繁体   English

如何测试与test :: unit的belongs_to,has_one或has_many关联?

[英]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. 我是Rails测试的新手,尝试过使用Shoulda,但是它破坏了我放入的任何模型,所以我认为我应该手动对其进行测试。

So my question to you oh great experts of SO is this: 所以我向您提出的问题,哦,SO的专家,是这样的:

How can I use test::unit to test that a model is associated with another model? 如何使用test :: unit测试一个模型与另一个模型相关联?

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) . 我只是检查user.respond_to?(:friends) But, of course, it will fail if someone defines a method with that name 但是,当然,如果有人用该名称定义方法,它将失败

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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