【问题标题】:How to test receipt of the same method with different arguments on different instances如何在不同实例上使用不同参数测试相同方法的接收
【发布时间】:2017-07-20 07:38:01
【问题描述】:

我有我的方法

def my_method
  MyClass.new.track(arg1, arg2)

  if satisfies_some_condition
    2.times { MyClass.new.track(arg3, arg4) }
  end
end

RSpec,我想测试#track 的收据

expect_any_instance_of(MyClass).to receive(:track).with(arg1, arg2)
expect_any_instance_of(MyClass).to receive(:track).with(arg3, arg4).twice

但是我收到了这个错误

#<MyClass:70362069595680 > 收到了“track”消息,但有 #<MyClass:0x007ffce788e460>已经收到了

似乎here 建议升级到RSpec-mocks v3.6.0 来解决,但是即使将我的RSpec-mocks gem 升级到v3.6.0 后我仍然遇到同样的错误

【问题讨论】:

    标签: ruby-on-rails ruby unit-testing rspec


    【解决方案1】:

    我从不喜欢any_instance,所以不知道如何用它来做你想做的事,但是,另一种可以做你想做的事情的替代方法是

    class MyClass
      def track(a, b)
      end
    end
    
    def my_method(pass = true)
      MyClass.new.track('a', 'b')
    
      if pass
        2.times { MyClass.new.track('c', 'd') }
      end
    end
    
    RSpec.describe "SO question" do
      it 'pass' do
        first = double(MyClass)
        expect(first).to receive(:track).with('a', 'b')
        second = double(MyClass)
        expect(second).to receive(:track).with('c', 'd').twice
    
        allow(MyClass).to receive(:new).and_return(first, second)
        my_method
      end
    
      it 'fail' do
        first = double(MyClass)
        expect(first).to receive(:track).with('a', 'b')
        second = double(MyClass)
        expect(second).to receive(:track).with('c', 'd').twice
    
        allow(MyClass).to receive(:new).and_return(first, second)
        my_method(false)
      end
    end
    

    有点冗长,但强制new 方法返回多个对它们有期望的实例。 and_return 将在每次调用时按顺序返回这些值,然后将继续返回最后一个值以进行任何其他调用。

    【讨论】:

    • 我尝试使用这个instances = Array.new(2) { double('Services::SegmentAnalytics') } 并使用实例[0] 和实例[1]。我想我对我正在尝试的所有混合 n 匹配有点困惑。谢谢,我从你的回答中明白了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 2013-10-15
    相关资源
    最近更新 更多