ruby 测试私有方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 测试私有方法相关的知识,希望对你有一定的参考价值。

# Poor specs
# ==========

describe CloseOrder do
  # Testing #call using partial double of object being tested 
  # looks unnatural and feels as a duplication
  describe '#call' do
    it do
      order = create(:order)
      service = CloseOrder.new(order)
      allow(service).to receive(:send_notification)
      
      service.call
      
      expect(service).to have_received(:send_notification)
    end
  end
  
  describe '#send_notification' do
    it 'delivers order closed notification to customer' do
      order = create(:order, customer_email: 'tony@stark.com')  
      service = CloseOrder.new(order)
    
      expect { 
        service.send(:send_notification) # We are forced to use #send to test private method
      }.to change { ActionMailer::Base.deliveries.count }.by(1)

      notification = ActionMailer::Base.deliveries.last
      expect(notification).to have_attributes(subject: 'Order closed!', recipients: ['tony@stark.com'])
    end
  end
end

# Good specs
# ==========

describe CloseOrder do
  describe '#call' do
    it 'delivers order closed notification to customer' do
      order = create(:order, customer_email: 'tony@stark.com')  
      service = CloseOrder.new(order)
    
      expect { 
        service.call 
      }.to change { ActionMailer::Base.deliveries.count }.by(1)

      notification = ActionMailer::Base.deliveries.last
      expect(notification).to have_attributes(subject: 'Order closed!', recipients: ['tony@stark.com'])
    end
  end
end

# Implementation
# ==============

class CloseOrder
  def initialize(order)
    @order = order
  end
  
  def call
    send_notification
  end
  
  private
  
  def send_notification
    OrderMailer.order_closed_notification(@order).deliver_now
  end  
end

以上是关于ruby 测试私有方法的主要内容,如果未能解决你的问题,请参考以下文章

澄清 Ruby 中“私有”和“受保护”的定义?

有没有办法从 Ruby 中的实例调用私有类方法?

ruby 顶层定义的方法在哪里?

Ruby 方法 instance_eval() 和 send() 不会否定私有可见性的好处吗?

为什么Ruby不允许我将self指定为私有方法中的接收者?

如何在 Ruby 中创建私有类常量