Rails/Rspec 存根:指定顺序和顺序依此类推
我很乐意创建基本的存根,但对如何指定诸如顺序(和反转它)等内容有点困惑。
举一个具体的例子,这里是我正在尝试测试的控制器中的一行
@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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您假设 ActiveRecord 将在某个时刻调用 Course.all,但情况可能并非如此。
试试这个:
为了避免进行链式存根,您可以将 ActiveRecord 代码移到模型中,这样控制器就会有更简单的东西,例如:
You're assuming that ActiveRecord will call Course.all at some point, which may not be the case.
Try this:
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: