使用 Sinatra 和 rspec 存根控制器方法

发布于 2024-08-14 15:14:47 字数 330 浏览 1 评论 0原文

所以我试图找出一种在 Sinatra 应用程序的 rspec 中存根控制器方法的方法。这样做的主要原因是测试应用程序的逻辑流程并确保在满足某些条件时调用必要的函数。所以,本质上,我希望能够做类似

controller.should_receive(:fancy_method).and_return("This is a string")

我遇到困难的是访问 sinatra 应用程序中的控制器实例之类的事情。我可以使用 sinatra 控制器类上的 class_eval 覆盖当前函数,但我很想断言这些函数实际运行。

有人有什么建议吗?

谢谢。

So I'm trying to figure out a way of stubbing a controller method in rspec for a Sinatra app. The main reason for this is to test the logical flow of the application and to make sure it calls the necessary functions when certain conditions are met. So, in essence, I want to be able to do something like

controller.should_receive(:fancy_method).and_return("This is a string")

What I'm having difficulty doing is accessing the controller instance within the sinatra app. I am able to override the current functions using a class_eval on the sinatra controller class, but I'd love to assert that these functions actually run.

Anyone have any advice?

Thanks.

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

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

发布评论

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

评论(1

缺⑴份安定 2024-08-21 15:14:47

丹,我相信你真正想要的是测试控制器的操作。从测试人员的角度来看,您不应该真正关心它实际调用的内容,而是关心输出,给定特定输入和也许一些其他特殊条件(即模拟或存根其他类)(1) 。

您可以查看 Sinatra + Rack::Test 官方文档这篇博文来自 devver.net

(1):如果您的控制器页面正在调用其他一些类(模型、服务等),您可以模拟这些类并对它们寄予期望。例如:

SomeClass.should_receive(:msg).with(:arg).and_return(:special_value)

有关模拟的更多信息(在此示例中使用 RSpec)可以在 RSpec 文档中找到页面

Dan, I believe what you really want is to just test the controller actions. From a tester's perspective you shouldn't really care about what it actually called but rather for the output, given a specific input and maybe some other special conditions (that is mocking or stubbing other classes) (1).

You can check the official documentation for Sinatra + Rack::Test or this blog post from devver.net.

(1) : If your controller pages are calling some other classes (models, services, etc) you could mock these instead and put expectations on them. For example :

SomeClass.should_receive(:msg).with(:arg).and_return(:special_value)

Some more info for mocking (with RSpec in this exmaple) can be found on the RSpec documentation pages.

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