[英]How to test if a method call with arguments happened in RSpec
In my Ruby app, I'm trying to test with RSpec a module method called with arguments from a controller. 在我的Ruby应用程序中,我试图用RSpec测试一个用控制器参数调用的模块方法。
The module in question is the EventTracker module to track analytics: https://github.com/doorkeeper/event_tracker 有问题的模块是用于跟踪分析的EventTracker模块: https : //github.com/doorkeeper/event_tracker
This is the situation: 情况就是这样:
From my controller I call the method from the controller like below: 从我的控制器我从控制器调用方法如下:
class InvestorHomeController < ApplicationController def do_something track_event 'User Action' end end
The track_event
method is defined inside the EventTracker
module, like the following: track_event
方法在EventTracker
模块中定义,如下所示:
module EventTracker module HelperMethods def track_event(event_name, args = {}) (session[:event_tracker_queue] ||= []) << [event_name, args] end end
end 结束
I tried different solutions, but nothing worked for me. 我尝试了不同的解决方案,但没有任何对我有用。 Like:
喜欢:
expect(controller).to receive(:track_event).with('User Action') expect(EventTracker).to receive(:track_event).with('User Action')
The first it didn't work because track_event
is not a method of the controller, and for the second one I've got the error below: 第一个它不起作用因为
track_event
不是控制器的方法,而对于第二个我得到了以下错误:
RSpec::Mocks::MockExpectationError: (EventTracker).track_event("User Action")
expected: 1 time with arguments: ("User Action")
received: 0 times
Anyone knows how to test this kind of methods with RSpec? 谁知道如何用RSpec测试这种方法?
Thanks, D. 感谢:D。
I've found the way to get this working! 我找到了让这个工作的方法!
Basically, I was doing everything right apart from doing the 'post' call in the right place. 基本上,除了在正确的位置进行“发布”呼叫之外,我做的一切都是正确的。
The post call have to be done after the: 后调用必须在以下后完成:
expect(controller).to receive(:track_event).with('User Action')
ie the code below will work without any problems: 即下面的代码将没有任何问题:
expect(controller).to receive(:track_event).with('User Action')
post :new_user_action_post
and not before. 而不是之前。
I hope will help someone! 我希望能帮助别人! ;)
;)
D. D.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.