【问题标题】:How to filter out one method call from many others with `expect().to receive()` in RSpec如何在 RSpec 中使用“expect().to receive()”过滤掉许多其他方法调用
【发布时间】:2019-08-17 11:20:31
【问题描述】:

我有这样的代码:

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 方法分析所有方法调用并选择参数匹配的那个,而不仅仅是最后一个?顺便说一句,这种行为让我感到困惑。

【问题讨论】:

    标签: ruby-on-rails-3 rspec


    【解决方案1】:

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

    在您的情况下,我猜您想测试您的方法是否返回“A”和“B”。

    我建议你编写一个返回“A”的方法和另一个返回“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了,那会有点矫枉过正。

    【讨论】:

    • 矫枉过正或 TDD - 我们可以争论。但是,是的,这是一个有效的解决方案:)
    猜你喜欢
    • 2022-10-23
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多