Ruby on rails 如何测试RSpec中是否发生了带参数的方法调用

Ruby on rails 如何测试RSpec中是否发生了带参数的方法调用,ruby-on-rails,ruby,rspec,Ruby On Rails,Ruby,Rspec,在我的Ruby应用程序中,我尝试使用RSpec测试一个模块方法,该方法使用来自控制器的参数调用 所讨论的模块是跟踪分析的EventTracker模块: 情况就是这样: 从我的控制器,我从控制器调用方法,如下所示: class InvestorHomeController < ApplicationController def do_something track_event 'User Action' end end 结束 我尝试了不同的解决方案,但都不管用。比如: ex

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

所讨论的模块是跟踪分析的EventTracker模块:

情况就是这样:

  • 从我的控制器,我从控制器调用方法,如下所示:

    class InvestorHomeController < ApplicationController
      def do_something
        track_event 'User Action'
      end
    end
    
    结束

  • 我尝试了不同的解决方案,但都不管用。比如:

    expect(controller).to receive(:track_event).with('User Action')
    expect(EventTracker).to receive(:track_event).with('User Action')
    
  • 第一个不起作用,因为
    track\u event
    不是控制器的方法, 对于第二个,我得到了下面的错误:

    RSpec::Mocks::MockExpectationError: (EventTracker).track_event("User Action")
    expected: 1 time with arguments: ("User Action")
    received: 0 times
    
    有人知道如何用RSpec测试这种方法吗

    谢谢,
    D.

    我找到了让它工作的方法

    基本上,除了写“帖子”,我什么都做对了 找对地方

    必须在以下时间后进行post通话:

    i、 e.以下代码将不会出现任何问题:

      expect(controller).to receive(:track_event).with('User Action')
      post :new_user_action_post
    
    而不是以前

    我希望能帮助别人


    D.

    我同意。。。您可能应该测试会话中添加的内容。谢谢大家的评论。是的,我以正确的方式测试了正确的东西,但实际上我是在expect(controller)之前调用了“post”。接收(:track_event)。使用('User Action'),这就是为什么不起作用!
      expect(controller).to receive(:track_event).with('User Action')
    
      expect(controller).to receive(:track_event).with('User Action')
      post :new_user_action_post