0
0
Ruby on Railsframework~30 mins

Model tests in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Model tests
📖 Scenario: You are building a simple Rails app to manage books in a library. Each book has a title and an author. You want to make sure your model works correctly by writing tests.
🎯 Goal: Write model tests for the Book model to check that it validates presence of title and author.
📋 What You'll Learn
Create a Book model with title and author attributes
Add presence validations for title and author
Write model tests to check these validations using RSpec
💡 Why This Matters
🌍 Real World
Model tests help ensure your data rules work correctly before saving to the database, preventing bad data and bugs.
💼 Career
Writing model tests is a key skill for Rails developers to maintain reliable and maintainable applications.
Progress0 / 4 steps
1
Create the Book model with attributes
Create a Rails model called Book with string attributes title and author using a migration.
Ruby on Rails
Need a hint?

Use rails generate model Book title:string author:string to create the model and migration.

2
Add presence validations to Book model
In the Book model, add presence validations for the title and author attributes using validates :title, presence: true and validates :author, presence: true.
Ruby on Rails
Need a hint?

Use validates :attribute, presence: true for each attribute.

3
Create RSpec model test file for Book
Create a new RSpec test file spec/models/book_spec.rb with a describe Book block to hold your model tests.
Ruby on Rails
Need a hint?

Use describe Book, type: :model do ... end to start the test file.

4
Write presence validation tests for Book model
Inside the describe Book block, write two tests using it blocks to check that title and author must be present. Use should validate_presence_of(:title) and should validate_presence_of(:author) matchers.
Ruby on Rails
Need a hint?

Use it { should validate_presence_of(:attribute) } syntax from shoulda-matchers gem.