0
0
RailsHow-ToBeginner · 3 min read

How to Use Minitest in Rails: Simple Guide with Examples

In Rails, minitest is the default testing framework that lets you write tests in files under test/. You create test classes inheriting from ActiveSupport::TestCase and define test methods starting with test_ to check your code behavior.
📐

Syntax

To write a Minitest test in Rails, create a class inheriting from ActiveSupport::TestCase. Define test methods starting with test_. Use assertions like assert or assert_equal to check expected outcomes.

  • class: Defines the test case class.
  • test_*: Method names starting with test_ are run as tests.
  • assert: Checks if a condition is true.
  • assert_equal: Checks if two values are equal.
ruby
class ExampleTest < ActiveSupport::TestCase
  def test_truth
    assert true
  end

  def test_sum
    assert_equal 4, 2 + 2
  end
end
💻

Example

This example shows a simple model test for a Rails User model. It checks if a user is valid with a name and if the name is present.

ruby
require 'test_helper'

class UserTest < ActiveSupport::TestCase
  def setup
    @user = User.new(name: "Alice")
  end

  def test_user_is_valid
    assert @user.valid?
  end

  def test_name_presence
    @user.name = ""
    assert_not @user.valid?
  end
end
Output
Run options: --seed 12345 # Running: .. Finished in 0.001234s, 1620.0000 runs/s, 2430.0000 assertions/s. 2 runs, 3 assertions, 0 failures, 0 errors, 0 skips
⚠️

Common Pitfalls

Common mistakes include not prefixing test methods with test_, which causes tests not to run, and forgetting to require test_helper which sets up the test environment. Also, using assert without a clear condition can lead to false positives.

ruby
require 'test_helper'

class WrongTest < ActiveSupport::TestCase
  def user_is_valid
    assert @user.valid?  # This won't run because method name lacks 'test_'
  end
end

# Correct way:
class RightTest < ActiveSupport::TestCase
  def test_user_is_valid
    assert @user.valid?
  end
end
📊

Quick Reference

CommandDescription
rails testRuns all tests in the test directory
rails test test/models/user_test.rbRuns tests in a specific file
assert conditionPasses if condition is true
assert_equal expected, actualPasses if expected equals actual
assert_not conditionPasses if condition is false

Key Takeaways

Minitest is Rails’ default testing framework using classes inheriting from ActiveSupport::TestCase.
Test methods must start with test_ to be recognized and run.
Use assertions like assert and assert_equal to verify code behavior.
Always require test_helper at the top of your test files.
Run tests with the rails test command to check your application.