RSpec 双存根

RSpec double - stub

我是 rspec 的新手。我正在使用 receive_message_chain 和存根方法链,它现在工作正常。

正在测试代码

Abc::ImportJob < ImportBaseJob
   
   def self.perform
     base_class_meth(param1, param2)
   end
end

Abc::ImportBaseJob

def base_class_meth(param1, param2)
 Book.to_be_published.find_each do |book|
    publish_report(book)
  end
end

def publish_report(book)
  Publishjob.perform
end

结束

rspec

before do
   allow(Book).to receive_message_chain(:to_be_published, :find_each).and_yield(book1)
end

现在我正在尝试摆脱 receive_message_chain 并在此处使用 double。

使用双精度的代码:

before do
  books_to_be_published = double('books_to_be_published')
  allow(Book).to receive(:to_be_published).and_return('books_to_be_published')
  allow(books_to_be_published).to receive(:find_each).and_yield(book1)
end

it 'should publish kafka message at event start' do
    expect(PublishJob).to receive(:new).with(book1)
    ABC::ImportJob.perform
  end
  

但是结果是 预计 1 次与争论 收到:0次

我哪里做错了。

不应该吗

allow(Book).to receive(:to_be_published).and_return(books_to_be_published)