0

我为一名工作人员编写了一个测试,该工作人员会收到电子邮件,然后对他们做一些事情:

Net::POP3.start('pop.gmail.com', 995, "xxx", "xxxx") do |pop|
  if pop.mails.empty?
    log "#{Time.now} No mail."
  else
    pop.each_mail do |mail|
      #do something
    end
  end
end

以这种方式存根的最佳方法是什么Net::POP3.start,它会在实际运行时返回类似的数据?

谢谢

迪基

编辑:

其余的工作/填写#do something看起来有点像这样:

Net::POP3.start('pop.gmail.com', 995, "xxx", "xxxx") do |pop|
  if pop.mails.empty?
    log "#{Time.now} No mail."
  else
    pop.each_mail do |mail|
      parse_mail mail.pop
    end
  end
end


def parse_mail(raw_email)
   email = Mail.new raw_email
   email.attachments
   email.from
   email.subject
end

我想出的解决方案是(这可能有点特定于您的需求):

Net::POP3.stub(:start).and_yield Net::POP3.new("a test string")
Net::POP3.any_instance.stub(:mails).and_return [Net::POPMail.new("test","test","test","test")]
Net::POPMail.any_instance.stub(:pop).and_return("a raw email string")

我真的不喜欢。

使用@SteveTurczyn 正在使用的一些技术对其进行重构。

4

1 回答 1

1

这是几封电子邮件的“幸福之路”......

require 'spec_helper'
module NET 
  module POP3
  end
end
describe "testing NET::POP3" do
  before do
    @mail1 = double('mail1')
    @mail2 = double('mail2')
    @mail3 = double('mail3')
    @pop = double('pop')
    @pop.stub_chain(:mails, :empty?).and_return false
    allow(@pop).to receive(:each_mail).and_yield(@mail1).and_yield(@mail2).and_yield(@mail3) 
    expect(NET::POP3).to receive(:start).and_yield(@pop)
  end
  describe "three emails pending" do
    it "will return a pop entity" do
      NET::POP3.start do |p|
        expect(p).to eq(@pop)
      end
    end
    it "pop will indicate that emails are not empty" do
      NET::POP3.start do |p|
        expect(p.mails.empty?).to be_false
      end
    end
    it "pop will contain three mails" do
      NET::POP3.start do |p|
        counter = 0
        p.each_mail do |m|
          counter += 1
          expect([@mail1, @mail2, @mail3]).to include(m)
        end
        expect(counter).to eq 3
      end
    end
  end

end
于 2014-06-13T13:53:51.610 回答