Rashmi Balkur
Rashmi Balkur

Reputation: 337

How to write RSpec test cases for TimeOutError Exception

I have written retry logic for sending mails and trying to cover test cases for it.

def send_mail(mail,log_obj)
    begin
      attempts ||= 1
      mail.deliver_now
    rescue Errno::ECONNREFUSED, Errno::ECONNRESET, Net::OpenTimeout, Net::ReadTimeout => e
      CommonLogger.input_log(log_obj,"Timeout: #{e} (attempt ##{ attempts })")
      if (attempts += 1) <= 4
        sleep(1)
        Rails.logger.info ("Retrying...")
        retry
      else
        Rails.logger.error("Retry attempts exceeded.")
        raise e
      end
    end
  end

Upvotes: 0

Views: 357

Answers (1)

Arctodus
Arctodus

Reputation: 5847

You can use and_raise to raise errors https://relishapp.com/rspec/rspec-mocks/docs/configuring-responses/raising-an-error

allow(mail).to receive(:deliver_now).and_raise(Net::OpenTimeout)
allow_any_instance_of(MailClass).to receive(:deliver_now).and_raise(Net::OpenTimeout)

Upvotes: 0

Related Questions