复杂的 Arel 查询和 RSpec 存根
假设我们有一段这样的代码:
def index
@posts = Post.where(:status => ACTIVE)
if params[:s]
@posts = Post.where("title like ?", "%#{params[:s]}%").order("title asc")
else
@posts = Post.limit(20).order("date desc")
end
end
在指定此操作时,我们可以为每个示例编写一个存根链,但如果我们想将注意力集中在其他地方,这样会限制我们很多。
当您不知道顺序或将调用多少个方法时,对 RSpec 进行复杂 Arel 查询存根的最佳方法是什么?
注意:我正在查看 Rails 3 和 Rspec 中的存根链式查询 我想我想要的是类似于stub_chain_with_in Different_order(:where, :order, :limit) 。
Let's say we have some piece of code like so:
def index
@posts = Post.where(:status => ACTIVE)
if params[:s]
@posts = Post.where("title like ?", "%#{params[:s]}%").order("title asc")
else
@posts = Post.limit(20).order("date desc")
end
end
When specing this action we could either write a stub chain for every example but this way it restrains us a lot if we want to focus somewhere else.
What's the best way to stub a complex Arel query for RSpec when you don't know the order or how many of the methods will be called?
NOTE: I was looking at Stubbing Chained Queries in Rails 3 and Rspec and what I think I want is something like stub_chain_with_indifferent_order(:where, :order, :limit)
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可能是代码告诉您您在错误的级别上执行此操作。这是我真正喜欢 RSpec 的“模拟所有事物(!!)”哲学的一点:如果它变得难以模拟,也许你的设计是错误的。
例如,我可能会将您的代码重构为:(
或者根据您的域稍微更好一些。)
然后您可以模拟
Posts.posts_for
,一个简单的方法调用,而不是尝试模拟大量AR 链接方法。This might be the code telling you that you are doing this at the wrong level. Which is something I really like about the MOCK ALL THE THINGS(!!) philosophy of RSpec: if it's getting hard to mock, maybe your design is wrong.
For example, I might refactor your code to be:
(Or something slightly better given your domain.)
Then you can mock out
Posts.posts_for
, a simple method call, instead of trying to mock a ton of AR chained methods.