如何存根named_scope,以便仍然可以在结果集上调用.find?

发布于 2024-12-14 16:41:27 字数 863 浏览 7 评论 0原文

我正在维护一个 Rails 应用程序。

控制器旧代码:

@articles = Articles.unpublished.find(complicated_conditions)

我将其更改为如下所示:

if logged_user.has_a_specific_permission
  @articles = Articles.unpublished.find(complicated_conditions)
else
  @articles = Articles.unpublished.find(another_hash_of_complicated_conditions)
end

我想为我的更改编写规范,但我不认为测试条件是测试该功能的最佳方法(但如果我错了,请纠正我) )。

因此,在我的规范中,我想要类似: 的

login_as(user_with_specific_permission)
permitted = stub('permitted article')
prohibited = stub('prohibited article')
Articles.stub!(:unpublished).and_return([permitted, prohibited])
get :index
assigns[:articles].should eql([permitted])

内容来测试条件是否按预期过滤结果,但这不起作用,因为我无法使用数组中的条件调用 .find 。

那么如何测试这个功能呢?

tl;dr: 我想存根方法链的第一部分,但我无法返回数组,而且我不知道应该返回什么。

I'm mantaining a Rails app.

Controller old code:

@articles = Articles.unpublished.find(complicated_conditions)

I'm changing it to something like this:

if logged_user.has_a_specific_permission
  @articles = Articles.unpublished.find(complicated_conditions)
else
  @articles = Articles.unpublished.find(another_hash_of_complicated_conditions)
end

I want to write a spec for my change but I don't think testing the conditions is the best way to test the feature (but please correct me if I'm wrong).

So in my spec I wanted to have something like:

login_as(user_with_specific_permission)
permitted = stub('permitted article')
prohibited = stub('prohibited article')
Articles.stub!(:unpublished).and_return([permitted, prohibited])
get :index
assigns[:articles].should eql([permitted])

, to test if the conditions are filtering the results as expected, but this doesn't work because I can't call .find with conditions in an Array.

So what's the way to test this feature?

tl;dr: I want to stub the first part of a method chain but I can't return an Array, and I don't know what I should return.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文