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

查看:20
本文介绍了检查 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 ?

推荐答案

由于 ActiveRecord 关联应该由 Rails 测试套件很好地测试(并且它们确实如此),大多数人认为不需要确保它们工作 -- 只是假设他们会.

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.

如果您想确保您的模型使用这些关联,那就是不同的东西,您想要测试它并没有错.我喜欢使用 should gem 来做到这一点.它可以让你做这样的事情:

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天全站免登陆