Testing exceptions with Minitest

Here's how we can test all kinds of exceptions and throughs in our POROs, models, and services.

Table of contents

Using assert_raises

Testing exceptions in Ruby on Rails applications using plain Minitest is an essential aspect of ensuring that your application behaves as expected in error scenarios. By testing for exceptions, you can verify that your code handles unexpected situations gracefully and provides appropriate feedback to users.

To test exceptions in a Ruby on Rails app with Minitest, you can use the assert_raises method provided by Minitest. This method allows you to specify the type of exception you expect to be raised during the execution of a particular block of code.

Here's an example of how you can test for exceptions in a Rails application using Minitest:

require 'test_helper'

class ExampleTest < ActiveSupport::TestCase
  def test_division_by_zero_raises_exception
    assert_raises ZeroDivisionError do
      5 / 0
    end
  end
end

In this example, we have a test case that checks if dividing a number by zero raises a ZeroDivisionError . The assert_raises method is used to run the block of code and verify that the specified exception is raised.

When writing tests for exceptions, it's important to consider various scenarios where exceptions might occur in your application. You can test for specific exceptions that your code is expected to raise, as well as handle unexpected exceptions by using a more general assertion.

Author
Josef Strzibny
Hello, I am Josef and I am on Rails since its 2.0 version. I always liked strong conventions and the Rails Omakase docrine. I am author of Kamal Handbook and Test Driving Rails. I think testing should be fun, not a chore.

© Test Driving Rails Blog