Concept Flow - Model tests
Write model code
Write test cases
Run tests
Tests pass?
No→Fix code or tests
Yes
Model behavior verified
This flow shows writing model code, creating tests, running them, and fixing issues until tests pass.
class User < ApplicationRecord validates :email, presence: true end user = User.new assert user.valid? == false
| Step | Action | Input/State | Output/Result |
|---|---|---|---|
| 1 | Create User instance | User.new(email: nil) | User object with email=nil |
| 2 | Validate user | user.valid? | false (email missing) |
| 3 | Set email | user.email = 'test@example.com' | email set |
| 4 | Validate user again | user.valid? | true (email present) |
| 5 | Test assertion | assert user.valid? | passes |
| 6 | Run test suite | all tests | success |
| 7 | End | tests passed | Model behavior confirmed |
| Variable | Start | After Step 1 | After Step 3 | Final |
|---|---|---|---|---|
| user.email | nil | nil | 'test@example.com' | 'test@example.com' |
| user.valid? | N/A | false | true | true |
Model tests check if your data rules work. Write validations in model (e.g., presence). Write tests creating model instances. Run tests to confirm model behaves right. Fix code/tests if tests fail. Repeat until tests pass.
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