Testing with Minitest

Minitest is small, fast, and the default in Rails. Benchmarks: Minitest::Benchmark.

# test/calculator_test.rb
require "minitest/autorun"
require_relative "../lib/calculator"

class CalculatorTest < Minitest::Test
  def setup
    @calc = Calculator.new
  end

  def test_add
    assert_equal 5, @calc.add(2, 3)
  end

  def test_divide_by_zero
    assert_raises(ZeroDivisionError) { @calc.divide(1, 0) }
  end

  def test_floats
    assert_in_delta 0.3, 0.1 + 0.2, 0.0001
  end

  def test_collections
    assert_includes [1, 2, 3], 2
    assert_empty []
    assert_nil nil
    assert_match(/\d+/, "abc123")
    refute @calc.negative?(5)
  end

  def test_with_stub
    Time.stub(:now, Time.at(0)) do
      assert_equal 1970, Time.now.year
    end
  end

  def test_mock
    mailer = Minitest::Mock.new
    mailer.expect(:deliver, true, ["[email protected]"])
    Notifier.new(mailer).notify("[email protected]")
    mailer.verify
  end
end

# Spec style
describe Calculator do
  it "adds numbers" do
    _(Calculator.new.add(1, 2)).must_equal 3
  end
end
ruby -Ilib -Itest test/calculator_test.rb
rake test