簡體   English   中英

如何在Ruby和RSpec中使用潛在的Nil類處理新方法

[英]How to deal with stubbing new method with potential Nil class in Ruby and rspec

我遇到的情況是,我對一個類的.new方法進行了存根處理,但是這使它返回了nil個對象,后來又需要這些對象,而且我不確定如何處理它。 這是我的rspec代碼:

describe ShopWorker do
  describe '#perform' do
    let(:worker) { ShopWorker.new }
    it 'creates a new instance of Shopper' do
      user = FactoryGirl.create(:user)
      expect(Shopper).to receive(:new).with(user)
      worker.perform(user.id)
    end
  end
end

這是我的工作程序代碼:

class ShopWorker
  include Sidekiq::Worker

  def perform(user_id)
    user = User.find(user_id)

    shopper = Shopper.new(user)
    shopper.start # This fails because Shopper.new returns NIL
  end
end

因此,由於我在新方法中使用了Expect expect(Shopper).to receive(:new).with(user) ,所以當在worker中使用shopper.start時,它為nil,因此會中斷。 我該如何解決? 理想情況下,我想測試是否完成了Shopper的新實例,並且還針對該實例調用了方法start。

您可以做幾件事:

  1. 期望收到:new但是使用and_return()提供一個返回值(可能是一個模擬and_return() 問題在於,除非您顯式提供返回值,否則to receive具有隱式的and_return(nil)
  2. 不要在任何Shopper實例上都存根:new ,讓它完成工作並期望:startexpect_any_instance_of(Shopper).to receive(:start)
  3. 問問自己該測試提供了什么價值。 該測試對實現非常了解,以至於您總是必須同時更改兩者。 shopper.start什么影響? 您能否斷言有關實際業務價值的任何事情?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM