Rails/Rspec 存根:指定顺序和顺序依此类推

发布于 2024-11-10 03:19:35 字数 675 浏览 0 评论 0原文

我很乐意创建基本的存根,但对如何指定诸如顺序(和反转它)等内容有点困惑。

举一个具体的例子,这里是我正在尝试测试的控制器中的一行

@courses = Course.order('created_at').reverse

:我的控制器规范,(显然失败的)存根是:

  Course.stub(:all) { [mock_course] }

...以及 rspec 错误:

  Failure/Error: assigns(:courses).should eq([mock_course])

       expected [#<Course:0x818614e8 @name="Course_1001">]
            got [#<Course id: 2, name: "Second test course", price: #<BigDecimal:1030e73c0,'0.4995E2',18(18)>]

尽管是一个不准确的测试(不是测试排序),但我猜测规范会通过。它不是——它是从数据库中提取的,而不是模拟的。 Soo...我想我要问的是,如何存根 Course.order('created_at').reverse ?

非常感谢...

I'm comfortable creating basic stubs, but a little confused about how to specify things such as order (and reversing it), etc.

To give a concrete example, here is a line in my controller that I'm trying to test:

@courses = Course.order('created_at').reverse

In my controller spec, the (obviously failing) stub is:

  Course.stub(:all) { [mock_course] }

...and the rspec error:

  Failure/Error: assigns(:courses).should eq([mock_course])

       expected [#<Course:0x818614e8 @name="Course_1001">]
            got [#<Course id: 2, name: "Second test course", price: #<BigDecimal:1030e73c0,'0.4995E2',18(18)>]

Despite being an inaccurate test (not testing ordering), i would have guessed the spec would pass. It doesn't - it's pulling from the database, not the mock. Soo...I guess what I'm asking is, how do I stub Course.order('created_at').reverse ?

Many thanks...

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

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

发布评论

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

评论(1

终遇你 2024-11-17 03:19:35

您假设 ActiveRecord 将在某个时刻调用 Course.all,但情况可能并非如此。

试试这个:

Course.stub_chain(:order, :reverse) { [mock_course] }

为了避免进行链式存根,您可以将 ActiveRecord 代码移到模型中,这样控制器就会有更简单的东西,例如:

Course.all_by_newest_first

You're assuming that ActiveRecord will call Course.all at some point, which may not be the case.

Try this:

Course.stub_chain(:order, :reverse) { [mock_course] }

To avoid having to do chained stubbing, you could move the ActiveRecord code into your model, so the controller would have something simpler such as:

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