【问题标题】:Rspec matcher to test a method calls another inside an each block用于测试方法的 Rspec 匹配器在每个块内调用另一个方法
【发布时间】:2021-05-15 10:54:33
【问题描述】:

我正在尝试测试一个 ruby​​ 方法在每个块中从它内部调用另一个方法

示例类

class A
  def foo
    return 'foo'
  end
end

class B
  def initialize
    @array_of_class_a_instances = []
  end

  def bar
    @array_of_class_a_instances.each do |element|
      element.foo
    end
  end
end

我想为 B 类中的 bar 方法编写一个单元测试,以验证 foo 方法被调用的次数是 @array_of_class_a_instances 长。如果我们说数组有 4 个元素,我想测试 foo 方法被调用了 4 次。我有一个可以在下面工作的测试,但它使用了多个期望语句。是否有一些语法可以只用一个来编写?

describe B do
  describe '#bar' do
    # ommitted for brevity
    small_b = B.new
    it 'calls the foo method for each element in the array' do
      expect(small_b.array_of_class_a_instances[0]).to receive(:foo).exactly(1).time
      expect(small_b.array_of_class_a_instances[1]).to receive(:foo).exactly(1).time
      expect(small_b.array_of_class_a_instances[2]).to receive(:foo).exactly(1).time
      expect(small_b.array_of_class_a_instances[3]).to receive(:foo).exactly(1).time
      small_b.bar
    end
  end
end

【问题讨论】:

    标签: ruby rspec mocking


    【解决方案1】:

    您也可以在测试中使用each

    small_b.array_of_class_a_instances.each do |instance|
      expect(instance).to receive(:foo).exactly(1).time
    end
    

    您还可以使用all 匹配器一次检查数组的所有元素。

    expect(small_b.array_of_class_a_instances).to all(receive(:foo).exactly(1).time)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-16
      • 2015-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多