在RSpec中检查ActiveRecord关联 [英] Checking ActiveRecord Associations in RSpec

查看:81
本文介绍了在RSpec中检查ActiveRecord关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何使用Rspec编写测试用例.我有一个简单的帖子注释支架,其中一个帖子可以包含很多注释.我正在使用Rspec对此进行测试.我应该如何检查Post :has_many :comments.我是否应该对Post.comments方法进行存根处理,然后通过返回注释对象数组的模拟对象来进行检查?是否真的需要测试AR关联?

I am learning how to write test cases using Rspec. I have a simple Post Comments Scaffold where a Post can have many Comments. I am testing this using Rspec. How should i go about checking for Post :has_many :comments. Should I stub Post.comments method and then check this with by returning a mock object of array of comment objects? Is testing for AR associations really required ?

推荐答案

由于应该由Rails测试套件对ActiveRecord关联进行充分的测试,因此大多数人都不需要确保它们可以正常工作- -只是假设他们会.

Since ActiveRecord associations should be well-tested by the Rails test suite (and they are), most people don't feel the need to make sure they work -- it's just assumed that they will.

如果您要确保模型使用的是 关联,那是不同的,并且想要测试它也没有错.我喜欢使用 shoulda 宝石来做到这一点.它可以让您做这样的整洁的事情:

If you want to make sure that your model is using those associations, that's something different, and you're not wrong for wanting to test that. I like to do this using the shoulda gem. It lets you do neat things like this:

describe Post do
  it { should have_many(:comments).dependent(:destroy) }
end

这篇关于在RSpec中检查ActiveRecord关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆