繁体   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