简体   繁体   English

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

[英]Stubbing a controller method with Sinatra and rspec

So I'm trying to figure out a way of stubbing a controller method in rspec for a Sinatra app. 所以我试图想出一种方法来为一个Sinatra应用程序在rspec中存储一个控制器方法。 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. 我遇到的困难是访问sinatra应用程序中的控制器实例。 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. 我能够使用sinatra控制器类上的class_eval覆盖当前函数,但我想断言这些函数实际运行。

Anyone have any advice? 有人有什么建议吗?

Thanks. 谢谢。

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). 从测试的角度来看,你不应该真正关心它实际上是所谓的,而是为输出,给出了具体的输入, 也许一些其他特殊情况(即嘲讽或磕碰其他类)(1)。

You can check the official documentation for Sinatra + Rack::Test or this blog post from devver.net . 您可以从devver.net 查看Sinatra + Rack :: Test此博客文章官方文档

(1) : If your controller pages are calling some other classes (models, services, etc) you could mock these instead and put expectations on them. (1):如果您的控制器页面正在调用其他类(模型,服务等),您可以模拟这些并对它们加以预期。 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 . 有关模拟的更多信息(在此例程中使用RSpec)可以在RSpec文档页面上找到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM