Performance: Model tests
Model tests affect development speed and test suite runtime, impacting developer feedback loops but not directly the page load or rendering speed.
setup do @user = User.new(name: 'Test', email: 'test@example.com', password: 'password') end test 'user is valid with all attributes' do assert @user.valid? end test 'user is invalid without email' do @user.email = nil assert_not @user.valid? assert_includes @user.errors[:email], "can't be blank" end
test 'user is valid with all attributes' do user = User.new user.name = 'Test' user.email = 'test@example.com' user.password = 'password' assert user.valid? end test 'user is invalid without email' do user = User.new(name: 'Test', password: 'password') assert_not user.valid? assert_includes user.errors[:email], "can't be blank" end
| Pattern | Database Operations | Test Runtime | Resource Usage | Verdict |
|---|---|---|---|---|
| Creating and saving full records repeatedly | Multiple writes and reads | High | High CPU and DB load | [X] Bad |
| Reusing setup objects without DB hits | Minimal or none | Low | Low CPU and DB load | [OK] Good |
| Testing associations with DB writes | Multiple writes and reads | High | High DB load | [X] Bad |
| Testing association presence without DB | No DB operations | Very Low | Minimal resource use | [OK] Good |
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