【问题标题】:Check if a method of a class is called from the method of the different class in rspec检查是否从rspec中不同类的方法调用了一个类的方法
【发布时间】:2021-12-06 19:21:44
【问题描述】:

假设有两个类:

1.

class Fax
  def initialize(number)
    **code**
  end

  def send!
    **code**
  end
end
class FaxJob
  def perform
    Fax.new(number).send!
  end
end

在 FaxJobSpec 中,我需要确认 FaxJob.perform_now(number) 运行 Fax.new(number).send!

【问题讨论】:

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


    【解决方案1】:

    您应该使用double。

    it 'sends fax!' do
      fax_instance = instance_double(Fax)
      allow(Fax).to(receive(:new).and_return(fax_instance))
      allow(fax_instance).to(receive(:send!))
    
      FaxJob.perform_now(number)
    
      expect(fax_instance).to(have_received(:send!))
    end
    

    您可以避免使用 allow 实例和类,只需对您的 Fax 类进行少量重构:

    class Fax
      def self.send!(number)
        new(number).send!
      end
    end
    

    FaxJob:

    class FaxJob
      def perform
        Fax.send!(number)
      end
    end
    

    然后你的测试:

    it 'sends fax!' do
      allow(Fax).to(receive(:send!).and_call_original)
    
      FaxJob.perform_now(number)
    
      expect(Fax).to(have_received(:send!).with(number))
    end
    

    如果你真的很喜欢 DRY,这应该也可以:

    it 'sends fax!' do
      expect(Fax).to(receive(:send!).with(number))
    
      FaxJob.perform_now(number)
    end
    

    我并没有真正找到后一个,因为它不尊重 AAA(排列、行为、断言)并且它损害了可读性,imo。

    【讨论】:

    • 获取 => #<InstanceDouble(Fax) (anonymous)> is a pure test double. "and_call_original" is only available on a partial double.
    • 对不起,伙计,我的错。刚刚更新了答案。但是你可以删除.and_call_original。
    猜你喜欢
    • 1970-01-01
    • 2016-11-16
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多