Search code examples
ruby-on-railsrubyminitest

Ruby: DEPRECATED: Use assert_nil if expecting nil. This will fail in Minitest 6


I am trying to run some test cases using Minitest in Ruby.

Here's the class that I am testing**:

# square_root.rb

class SquareRoot

  def square_root(value)
    return nil if value < 0
    Math.sqrt(value).round
  end
end

Here's my test case:

# square_root_test.rb

require 'minitest/autorun'

class SquareRootTest <Minitest::Test
  def test_that_square_root_of_9_is_3
    assert_equal 3, square_root(9)
  end

  def test_that_square_root_of_17_is_4
    assert_equal 4, square_root(17)
  end

  def test_that_square_root_of_24_is_5
    assert_equal 5, square_root(24)
  end

  def test_that_square_root_of_negative_number_is_nil
    assert_equal nil, square_root(-1)
  end
end

But when I run the command below to run the test:

ruby square_root_test.rb

I get the deprecation warning below:

Run options: --seed 50741

# Running:

DEPRECATED: Use assert_nil if expecting nil from square_root_test.rb:26. This will
fail in Minitest 6.
....

Finished in 0.000839s, 4769.9228 runs/s, 4769.9228 assertions/s.
4 runs, 4 assertions, 0 failures, 0 errors, 0 skips

Solution

  • Here's how I fixed it:

    Following the message from the deprecation warning, I simply replaced the assertion:

    assert_equal nil, square_root(-1)
    

    with

    assert_nil square_root(-1)
    

    OR

    assert_nil(square_root(-1))
    

    So my test file looked like this afterwards:

    # square_root_test.rb
    
    require 'minitest/autorun'
    
    class SquareRootTest <Minitest::Test
      def test_that_square_root_of_9_is_3
        assert_equal 3, square_root(9)
      end
    
      def test_that_square_root_of_17_is_4
        assert_equal 4, square_root(17)
      end
    
      def test_that_square_root_of_24_is_5
        assert_equal 5, square_root(24)
      end
    
      def test_that_square_root_of_negative_number_is_nil
        assert_nil square_root(-1)
      end
    end
    

    Note: That the comma , punctuation mark was removed as well.

    That's all.

    I hope this helps