【问题标题】:RSpec - Check if method was called further down(up?) the call stackRSpec - 检查方法是否被进一步调用(向上?)调用堆栈
【发布时间】:2020-11-13 17:16:42
【问题描述】:

我一直在使用内置的 Rails 测试套件,现在正在转向 RSpec 进行测试。我试图弄清楚是否在调用另一个方法的过程中调用了一个方法。 例如,我的 update_service.call 方法被一个对象调用。 update_service 调用 manage_service.call 方法。我正在尝试测试是否曾调用过 manage_service.call 方法。

expect(@update_service).to receive(:call).with(object).at_least(:once)
expect(@manage_service).to receive(:call).with(object.id).at_least(:once)

@update_service.call(encounter)

使用此设置,我遇到以下故障:

    Failures:

  1) UpdateService should call manage_service
     Failure/Error: expect(@manage_service).to receive(:call).with(object.id).at_least(:once)
     
       (#<ManageService:0x00007ffaf8c76190 @sdi=ServiceDI>).call(1)
           expected: at least 1 time with arguments: (1)
           received: 0 times
        # ....

我不确定我在这里缺少什么。

【问题讨论】:

    标签: ruby-on-rails ruby testing rspec


    【解决方案1】:

    RSpec 允许您使用any_instance_of 匹配器集进行设置。 如果您需要执行这种特定类型的测试并且无法通过 DI 手动指定实例,这将非常有用。

    expect_any_instance_of(Widget).to receive(:name).and_return("Wobble")

    见here

    【讨论】:

    • 此外,如果您不想指定值,则不需要指定值,而是可以通过 .and_call_original 调用原始实现
    猜你喜欢
    • 2021-09-12
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 2014-02-11
    • 2020-08-29
    • 2019-08-24
    相关资源
    最近更新 更多