0
0
Rubyprogramming~7 mins

Minitest basics (assert style) in Ruby

Choose your learning style9 modes available
Introduction

Minitest helps you check if your Ruby code works correctly by running small tests. Using assert style means you write simple true/false checks.

When you want to make sure a method returns the right result.
When you want to catch mistakes early by testing small parts of your code.
When you want to automatically check your code after changes.
When you want to learn how to write tests in Ruby easily.
Syntax
Ruby
require 'minitest/autorun'

class TestExample < Minitest::Test
  def test_something
    assert condition, 'optional failure message'
  end
end

assert checks if the condition is true.

If the condition is false, the test fails and shows the message.

Examples
Checks if 5 is greater than 3, which is true, so test passes.
Ruby
assert 5 > 3
Checks if the string 'hello' contains 'h'.
Ruby
assert 'hello'.include?('h')
This test will fail and show 'Math is broken!' because 2 + 2 is not 5.
Ruby
assert 2 + 2 == 5, 'Math is broken!'
Sample Program

This program has three tests. Two will pass because the math is correct. One will fail to show how Minitest reports errors.

Ruby
require 'minitest/autorun'

class TestMath < Minitest::Test
  def test_addition
    assert 2 + 2 == 4, 'Addition should work'
  end

  def test_subtraction
    assert 5 - 3 == 2
  end

  def test_fail_example
    assert 1 == 0, 'This test will fail'
  end
end
OutputSuccess
Important Notes

Use assert for simple true/false checks.

For checking equality, you can also use assert_equal expected, actual for clearer messages.

Run your tests from the command line with ruby your_test_file.rb.

Summary

Minitest assert style lets you write simple tests that check if conditions are true.

Tests help catch mistakes early and keep your code working well.

Use clear messages to understand why a test fails.