Introduction
Model tests check if your data rules work correctly. They help catch mistakes early.
Model tests check if your data rules work correctly. They help catch mistakes early.
require 'rails_helper' describe ModelName, type: :model do it 'does something expected' do expect(subject.some_method).to eq(expected_result) end end
describe to group tests for one model.it blocks to define individual test cases.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
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
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
This example tests that an Article needs a title to be valid. It shows one valid and one invalid case.
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
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.
Model tests check your data rules and methods.
Write tests for validations and important model logic.
Run tests often to catch errors early.
model tests in a Rails application?name using RSpec?validate_presence_of(:attribute) used with expect(model).RSpec.describe User, type: :model do
it 'is invalid without email' do
user = User.new(email: nil)
expect(user).not_to be_valid
end
endemail: nil, meaning no email is given.user to NOT be valid, so it checks that missing email makes the user invalid.it 'validates presence of title' do post = Post.new(title: '') expect(post).to be_valid end
title.title, empty string is invalid, but test expects valid, causing failure.title is empty but test expects valid -> Option Afull_name in your User model that combines first_name and last_name. Which is the best way to write this model test?full_name to return combined string is correct.user.full_name to equal their combination -> Option BPass the test and this pattern moves unknown