如何测试带参数的方法调用是否发生在 RSpec

How to test if a method call with arguments happened in RSpec

在我的 Ruby 应用程序中,我正在尝试使用 RSpec 一个使用来自控制器的参数调用的模块方法进行测试。

有问题的模块是用于跟踪分析的 EventTracker 模块:https://github.com/doorkeeper/event_tracker

情况是这样的:

  1. 从我的控制器调用方法如下:

    class InvestorHomeController < ApplicationController
      def do_something
        track_event 'User Action'
      end
    end
    
  2. track_event方法定义在EventTracker模块内部,如下所示:

    module EventTracker
      module HelperMethods
        def track_event(event_name, args = {})
          (session[:event_tracker_queue] ||= []) << [event_name, args]
      end
    end
    

    结束

  3. 我尝试了不同的解决方案,但没有任何效果。喜欢:

    expect(controller).to receive(:track_event).with('User Action')
    expect(EventTracker).to receive(:track_event).with('User Action')
    

第一个没用,因为track_event不是controller的方法, 对于第二个,我得到了以下错误:

RSpec::Mocks::MockExpectationError: (EventTracker).track_event("User Action")
expected: 1 time with arguments: ("User Action")
received: 0 times

有人知道如何用 RSpec 测试这种方法吗?

谢谢, D.

我找到了实现此功能的方法!

基本上,除了'post',我什么都做对了 在正确的地方调用。

post 调用必须在 之后完成:

  expect(controller).to receive(:track_event).with('User Action')

即下面的代码可以正常工作:

  expect(controller).to receive(:track_event).with('User Action')
  post :new_user_action_post

而不是之前。

希望对大家有所帮助! ;)

D.