Rails 3,RSpec 2.5:在命名范围内使用should_receive或stub_chain [英] Rails 3, RSpec 2.5: Using should_receive or stub_chain with named scopes

查看:94
本文介绍了Rails 3,RSpec 2.5:在命名范围内使用should_receive或stub_chain的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Rails 3.0.4和RSpec 2.5.例如,在我的控制器中,我大量使用命名作用域

I use Rails 3.0.4 and RSpec 2.5. In my controllers I use named scopes heavily, for example


   @collection = GuestbookEntry.nonreplies.bydate.inclusive.paginate(
       :page => params[:page], :conditions => { ... })

在我的测试中,我希望能够模拟这样的查询的结果,而不是 wording .我认为做类似的事情没有道理

In my tests, I want to be able to mock the result of such a query, not the wording. I do not think it makes sense to do something like


   GuestbookEntry.stub_chain(:nonreplies, :bydate, ...).and_return(...)

因为该测试在我决定重新命名命名范围时会失败.

because this test will fail the moment I decide to reorder the named scopes.

使用Rails 2.3和RSpec 1.x,可以很好地工作:我可以写

With Rails 2.3 and RSpec 1.x, this worked fine: I could write


   GuestbookEntry.should_receive(:find).with(:all, :conditions => { ... })

,上面的调用将被捕获并正确处理.但是,对于Rails 3,由于某种原因,它不再起作用.

and the above call would be caught and correctly handled. However, with Rails 3, for some reason this does not work any more.

为什么?如何在嵌套范围的结果中设置期望或存根?由于Rails 3的ActiveModel中的所有内容都是一个命名作用域(这要归功于ARel),因此必须能够以某种方式实现,否则测试确实非常脆弱.

Why? How do I set expectations or stubs on the result of nested scopes? Since everything in Rails 3's ActiveModel is a named scope (thanks to ARel), this must be possible somehow, or tests would indeed be very brittle.

谢谢!

更新:另请参见有关GitHub的问题报告.

推荐答案

这个问题也困扰了我一段时间!

This problem has bugged me for a while too!

我相信行为与Rails 2不同的原因是因为在控制器中的变量分配期间不再执行查询.相反,它是根据需要延迟加载的.

I believe the reason the behaviour is different from Rails 2 is because the query is no longer being performed during the variable assignment in the controller. Instead, it's lazy-loaded as required.

我同意马克·怀尔德(Mark Wilden)的观点,最好将所有这些范围包装在模型中更大的范围和规格中.该作用域显然具有特定功能,因此就像指定一个调用其他几种方法的方法的行为一样,您也将指定连接了其他几个作用域的作用域的行为.

I agree with Mark Wilden that it's better to wrap all of these scopes in a larger scope and spec that in your model. This scope clearly has a specific function, so just as one would spec the behaviour of a method which calls several other methods, you would spec the behaviour of a scope that joins several other scopes.

这篇关于Rails 3,RSpec 2.5:在命名范围内使用should_receive或stub_chain的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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