如何在 RSpec 中使用 `expect().to receive()` 从许多其他方法调用中过滤掉一个方法调用

How to filter out one method call from many others with `expect().to receive()` in RSpec

我有这样一段代码:

class ClassB
  def print_letter(arg)
  end
end

class ClassA
  def self.my_method
    ClassB.print_letter("a")
    ClassB.print_letter("b")
  end
end

RSpec.describe ClassA do
  describe "self.my_method" do
    it "prints a" do
      allow(ClassB)
      expect(ClassB).to receive(:print_letter).once.with("a")
      described_class.my_method
    end
  end
end

我失败了:

#<ClassB (class)> received :print_letter with unexpected arguments
  expected: ("a")
       got: ("b")

我能用它做些什么吗?有什么方法可以强制 receive 方法分析所有方法调用并选择参数匹配的那个,而不仅仅是最后一个?顺便说一句,这种行为让我感到困惑。

将一种责任赋予一种方法是一种很好的做法。

在您的情况下,我猜您想测试您的方法 return "A" 以及 "B".

我建议你写一个方法 return "A" 和另一个 return "B".

def print_a
  ClassB.print_letter("a")
end

def print_b
  ClassB.print_letter("b")
end

def self.my_method
    print_a
    print_b
  end

然后单独测试你的方法,例如:

it " Print a" do
  expect(print_a).to eq 'a'
end

这样你就不需要测试你的self.my_method了,这样就大材小用了。