如何构建我的测试以便测试我的救援条款?

时间:2016-03-15 22:59:57

标签: ruby-on-rails mocha minitest

我在编写测试时遇到一些困难,看看我的rescue子句中的方法是否被调用。这是我的代码:

 def run
    begin
      fail BounceLimitError, 'Reached 5% Bounce Rate' if Reverification::Process.bounce_limit_reached?
    rescue
      Reverification::Process.start_polling_queues
    end
    resend_soft_bounced_notifications
    send_notifications
  end

测试文件:

it 'should not invoke notifications sending methods when bounce limit is > 5%' do
  Reverification::Process.stubs(:bounce_limit_reached?).returns(true)
  Reverification::Mailer.expects(:send_notifications).never
  Reverification::Mailer.expects(:resend_soft_bounced_notifications).never

  assert_raise Reverification::Mailer::BounceLimitError do
    Reverification::Process.expects(:start_polling_queues)
    Reverification::Mailer.run
  end
end

我查阅了文档,assert_raise是要走的路,但是这个测试产生了不满意的期望。有人可以帮我弄清楚如何让这个测试成功吗?

----- ------ EDIT

我尝试使用以下代码推荐的更改:

  def run
    fail BounceLimitError, 'Reached 5% Bounce Rate' if Reverification::Process.bounce_limit_reached?
    resend_soft_bounced_notifications
    send_notifications
  rescue
    Reverification::Process.start_polling_queues
  end

 it 'should not invoke notifications sending methods when bounce limit is > 5%' do
  Reverification::Process.stubs(:bounce_limit_reached?).returns(true)
  Reverification::Mailer.expects(:send_notifications).never
  Reverification::Mailer.expects(:resend_soft_bounced_notifications).never
  Reverification::Process.expects(:start_polling_queues)
  Reverification::Mailer.run
end

当我执行测试时,错误就是抛出了异常。

1) Error:

run#test_0001_should not invoke notifications sending methods when bounce limit is > 5%:
Reverification::Mailer::BounceLimitError: Reached 5% Bounce Rate
    lib/reverification/mailer.rb:18:in `run'
    test/lib/reverification/mailer_test.rb:38:in `block (2 levels) in <class:MailerTest>'

测试正在通过,因为错误被抛出,但我怎么能通过呢?

1 个答案:

答案 0 :(得分:0)

在此实例中,

assert_raise不是您想要的,因为您的run方法不会产生该异常。在内部,它从中拯救并调用Reverification::Process.start_polling_queues方法。

在您的测试中,调用Reverification::Process.expects(:start_polling_queues)足以覆盖该代码路径(以及其他方法上的.never)。

那是:

  1. Reverification::Process.bounce_limit_reached?返回true
  2. 引发异常
  3. 发现异常
  4. Reverification::Process.start_polling_queues被称为
  5. PS:@PJSCopeland有一个好点,你的方法可能不正确。我想这可能是你想要做的事情:

    def run
      fail BounceLimitError, 'Reached 5% Bounce Rate' if Reverification::Process.bounce_limit_reached?
    
      resend_soft_bounced_notifications
      send_notifications
    rescue BounceLimitError
      Reverification::Process.start_polling_queues
    end
    

    如果可行,我建议这个版本不依赖于在同一方法中从异常中提升和抢救:

    def run
      Reverification::Process.start_polling_queues and return if Reverification::Process.bounce_limit_reached?
    
      resend_soft_bounced_notifications
      send_notifications
    end
    

    那应该通过你更新的单元测试。