0
0
Ruby on Railsframework~5 mins

Model tests in Ruby on Rails

Choose your learning style9 modes available
Introduction

Model tests check if your data rules work correctly. They help catch mistakes early.

When you want to make sure data saved to the database follows your rules.
When you add new validations or methods to your model.
When you fix bugs related to data handling in your app.
Before deploying changes that affect how data is stored or used.
Syntax
Ruby on Rails
require 'rails_helper'

describe ModelName, type: :model do
  it 'does something expected' do
    expect(subject.some_method).to eq(expected_result)
  end
end
Use describe to group tests for one model.
Use it blocks to define individual test cases.
Examples
This test checks if a user with correct data is valid.
Ruby on Rails
describe User, type: :model do
  it 'is valid with valid attributes' do
    user = User.new(name: 'Alice', email: 'alice@example.com')
    expect(user).to be_valid
  end
end
This test ensures a product must have a name.
Ruby on Rails
describe Product, type: :model do
  it 'is invalid without a name' do
    product = Product.new(name: nil)
    expect(product).not_to be_valid
  end
end
This test checks a method that sums prices.
Ruby on Rails
describe Order, type: :model do
  it 'calculates total price correctly' do
    order = Order.new
    order.add_item(price: 10, quantity: 2)
    expect(order.total_price).to eq(20)
  end
end
Sample Program

This example tests that an Article needs a title to be valid. It shows one valid and one invalid case.

Ruby on Rails
require 'rails_helper'

describe Article, type: :model do
  it 'is valid with a title and content' do
    article = Article.new(title: 'Hello', content: 'World')
    expect(article).to be_valid
  end

  it 'is invalid without a title' do
    article = Article.new(title: nil, content: 'World')
    expect(article).not_to be_valid
  end
end
OutputSuccess
Important Notes

Run model tests with bin/rails test or rspec if using RSpec.

Keep tests small and focused on one thing at a time.

Use factories or fixtures to create test data easily.

Summary

Model tests check your data rules and methods.

Write tests for validations and important model logic.

Run tests often to catch errors early.