复杂的 Arel 查询和 RSpec 存根

发布于 2024-11-27 10:46:53 字数 614 浏览 1 评论 0原文

假设我们有一段这样的代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

假装不在乎 2024-12-04 10:46:53

这可能是代码告诉您您在错误的级别上执行此操作。这是我真正喜欢 RSpec 的“模拟所有事物(!!)”哲学的一点:如果它变得难以模拟,也许你的设计是错误的。

例如,我可能会将您的代码重构为:(

def index
  @posts = Post.posts_for(:like => params[:s], :order => (params[:s] ? "title asc" : "date desc")
end

或者根据您的域稍微更好一些。)

然后您可以模拟 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:

def index
  @posts = Post.posts_for(:like => params[:s], :order => (params[:s] ? "title asc" : "date desc")
end

(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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文