Create Task Manager app: Setup backend – Rails models, tables, enums and add Rspec Tests

Create the User model

Now let’s start building our actual Rails application.

I want to start with the User model rather than Task, because our application will have JWT authentication and every task must belong to an authenticated user. We’ll introduce RefreshSession when we implement JWT refresh tokens.

Install bcrypt

Rails provides has_secure_password, which uses bcrypt for password hashing.

Uncomment this to backend/Gemfile: gem "bcrypt", "~> 3.1.7" and do bundle install

Why bcrypt?

We should never store users’ actual passwords in the database. Instead, bcrypt hashes the password using a salt. Rails provides password authentication functionality through has_secure_password. We’ll explore password hashing, verification and authentication in detail when implementing JWT login.

Generate User model

rails g model User email:string password_digest:string
      invoke  active_record
      create    db/migrate/20261117085319_create_users.rb
      create    app/models/user.rb
      invoke    rspec
      create      spec/models/user_spec.rb

Notice invoking rspec, because we configured rspec generators. Notice that we’re using password_digest, not password. has_secure_password provides a virtual password attribute and stores its hash in password_digest

Review the migration

Make these database-level changes:

  • email must not be NULL.
  • password_digest must not be NULL.
  • Add a unique, case-insensitive index for email.
class CreateUsers < ActiveRecord::Migration[8.1]
  def change
    create_table :users do |t|
      t.string :email, null: false
      t.string :password_digest, null: false

      t.timestamps
    end

    add_index :users, "lower(email)", unique: true, name: :idx_users_lower_email
  end
end

Run:

rails db:prepare -t 

Inspect db/schema.rb. You should see the users table with the expected columns and index.

Checklist

  • Add bcrypt to Gemfile.
  • Generate User model.
  • Add database constraints.
  • Add case-insensitive unique email index.
  • Run migrations successfully.
  • Inspect schema.rb.
  • Commit changes.

We’ll introduce has_secure_password, email normalization, validations, described_class, build_stubbed vs new and proper model specs. We’ll also begin understanding how RSpec interacts with ActiveRecord and PostgreSQL.

Let’s implement our first real Rails model behaviour and write meaningful RSpec tests against it.

User model, validations and password security

in User model add: has_secure_password

What does this provide? When you assign: user.password = "my-secret-password" Rails automatically generates a bcrypt password digest and stores it in: user.password_digest

It also provides: user.authenticate("my-secret-password")

The behaviour is:

InputResult
Correct passwordReturns the user object
Incorrect passwordReturns false

Important things to understand:

has_secure_password provides these validations automatically:

  • Password must be present when creating a new record.
  • Password cannot exceed 72 bytes.
  • Password confirmation is checked when you supply password_confirmation.

It does not enforce a minimum password length or complexity. We’ll discuss our password policy when implementing registration. Also, bcrypt’s 72-byte limit is a byte limit, not necessarily a 72-character limit.

Normalize the email address

onsider these inputs:

"Abhilash@Example.com"
" abhilash@example.com "
"ABHILASH@EXAMPLE.COM"

We want to store a consistent representation: abhilash@example.com

Rails provides an attribute normalization API. Add this to your model:

normalizes :email, with: ->(email) { email.strip.downcase }

Why use normalizes?

  • Normalization happens when an attribute is assigned or validated.
  • It keeps email representation consistent.
  • You don’t need to remember to call .strip.downcase in every controller.

Rails has supported normalizes since Rails 7.1.

Add email validations

Add validations for:

  • Email presence.
  • Email uniqueness, case-insensitive.

Use Rails validations rather than implementing custom validation methods for these requirements.

Important architectural distinction:

We’re using two protections for uniqueness:

  1. ActiveRecord uniqueness validation – provides a useful validation error to the application.
  2. PostgreSQL unique index – protects the database against concurrent duplicate inserts.

Neither replaces the other.

Note: Our earlier lower(email) unique index is important here. The validation and database constraint must enforce the same case-insensitive uniqueness rule.

Understand the complete model behaviour

Your model should now have three responsibilities:

User
 ├── Password security
 │    └── has_secure_password
 │
 ├── Email normalization
 │    └── normalizes
 │
 └── Email validations
      ├── presence
      └── case-insensitive uniqueness

Prepare RSpec model testing

described_class

Instead of writing: User.new(...)

inside every example, we can use: described_class.new(...)

When we write: RSpec.describe User do

described_class refers to User

Why is this useful?

Imagine we later rename the model or move the spec. Using described_class reduces unnecessary references to the class name.

Open:backend/spec/models/user_spec.rb

new vs create!

We’ll use native ActiveRecord methods for now, before introducing FactoryBot.

MethodBehaviour
User.newCreates an unsaved ActiveRecord object
User.createCreates and attempts to persist a record
User.create!Persists or raises an exception if validations fail
user = User.new(email: "test@example.com")
user.persisted? # false

# whereas:
user = User.create!(...)
user.persisted? # true

For a model uniqueness test, we need a persisted record to check against. We’ll introduce FactoryBot later and understand build, create and build_stubbed.

RSpec assignment

Implement these tests. We can use subject, let, context and before wherever appropriate. Refer: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/

Exercise 1 – Valid user

Create a user with a valid email and password. Verify that the user is valid.

Exercise 2 – Email presence

Test what happens when:

  • Email is missing.
  • Email is an empty string.

Verify the appropriate validation error.

Exercise 3 – Email uniqueness

This is important. Create a user with: abhilash@example.com

Then attempt to create another user using: ABHILASH@EXAMPLE.COM

Verify that the second user is invalid. Why are we testing this?

Because email uniqueness should be case-insensitive.

Exercise 4 – Email normalization

Pass this value: " Abhilash@Example.com " Verify that the resulting email is: abhilash@example.com

Also test that uppercase input is normalized.

Exercise 5 – Password digest

Create a user with a password.

Verify:

  • password_digest is present.
  • password_digest does not equal the original password.
  • The password digest is stored, not the plain-text password.

Exercise 6 – Password authentication

Test both scenarios:

Correct password:
user.authenticate("correct-password")
Expected: returns the user

Incorrect password:
user.authenticate("wrong-password")
Expected: returns false

Exercise 7 – Password confirmation

Try assigning:

password = "password123"
password_confirmation = "different-password"

Verify that the user is invalid.

Remember: Rails only checks confirmation when password_confirmation is supplied.

User Spec spec/models/user_spec.rb:

require 'rails_helper'

RSpec.describe User, type: :model do
  let(:valid_user) { described_class.create!(email: "email@example.com", password: "password@1") }
  let(:non_persisted_user) { described_class.new(email: "  EMAIL@example.com  ", password: "Pass12#") }

  describe "validations" do
    context "valid user" do
      it "check valid user" do
        expect(non_persisted_user.valid?).to be_truthy
      end
  
      it "check email, password presence" do
        non_persisted_user.valid?
        expect(non_persisted_user.email).not_to be_empty
        expect(non_persisted_user.password).not_to be_empty
      end
    end

    context "invalid user" do
      it "missing email, password, password digest" do
        invalid_user = described_class.new(email: "", password: "")
        invalid_user.valid?
        expect(invalid_user.errors.full_messages).to include("Email can't be blank")
        expect(invalid_user.errors.full_messages).to include("Password can't be blank")
        expect(invalid_user.errors.full_messages).to include("Password digest can't be blank")
      end

      it "throw error email not unique" do
        valid_user
        invalid_user = described_class.new(email: " EMAIL@EXAMPLE.com", password: "password@1")
        invalid_user.valid?
        expect(invalid_user.errors.full_messages).to include("Email has already been taken")
      end
    end
  end

  describe "email normalization" do
    it "email normalization when validation happens" do
      non_persisted_user.valid?
      expect(non_persisted_user.email).to eq("email@example.com")
    end

    it "email normalization when assignment" do
      new_user = described_class.new
      new_user.email = "  MYEMAIL@GMAIL.COM "
      expect(new_user.email).to eq("myemail@gmail.com")
    end

    it "checks email normalized after saving" do
      non_persisted_user.save!
      expect(non_persisted_user.email).to eq("email@example.com")
    end
  end

  describe "Passwords" do
    context "Passwords authentication" do
      it "checks valid authentication if email and password provided" do
        result = valid_user.authenticate("password@1")
        expect(result).to equal(valid_user)
      end
  
      it "checks invalid authentication if wrong password given" do
        result = valid_user.authenticate("wrong-pass12")
        expect(result).to be(false)
      end
    end

    context "Password digest" do
      it "checks password digest is present" do
        expect(valid_user.password_digest).not_to be_empty
      end

      it "password digest does not equal the original password" do
        expect(valid_user.password_digest).not_to eq(valid_user.password)
      end

      it "The password digest is stored, not the plain-text password" do
        # expect(valid_user.password_digest).
      end
    end
  end
end

Q): How does let caching work?

This is an important concept.

RSpec memoizes let values per example (it), not across examples.

Consider:

let(:user) do
  puts "Creating user"
  described_class.create!(
    email: "test@example.com",
    password: "password123"
  )
end

Now imagine three examples:

it "example 1" do
  user
  user
end

it "example 2" do
  user
end

it "example 3" do
  user
end

The execution looks like this:

Example 1
   |
   v
Access user
   |
   v
Execute let block (1st time)
   |
   v
Cache the result
   |
   v
Access user again
   |
   v
Return cached object
   |
   v
Example ends - cache discarded

Example 2
   |
   v
Access user
   |
   v
Execute let block again (2nd time)
   |
   v
Cache the result
   |
   v
Example ends - cache discarded

Example 3
   |
   v
Access user
   |
   v
Execute let block again (3rd time)
   |
   v
Cache the result

So the output will be:

Creating user
Creating user
Creating user

Key concept The user object is cached within one example, but a new object is created for every subsequent example that accesses user.

What about let!?

Exactly the same memoization, but with eager evaluation.

let!(:user) do
  puts "Creating user"
  described_class.create!(...)
end

The block executes automatically before every example.

Even if you never reference user inside the example, it is still created.

Behaviourletlet!
Lazy evaluationYesNo
Automatic evaluationNoYes
Memoized within exampleYesYes
Cached across examplesNoNo
Executes again in next exampleWhen referencedAlways

Important: RSpec’s memoization is unrelated to Rails caching (Rails.cache) or database caching. It only caches the helper’s return value for the current example.

There is too much test cases for a small user model snippet. So how big the test will be if the user model evolves and becomes big.

Q) Is it worth spending these much time spending test examples or do we write only the major ones in real world?

We deliberately wrote more examples than we’d probably write for such a small model in a real project. The objective was to teach you RSpec matchers, setup, validations, memoization and password testing.

In real-world development, we don’t write tests for every possible combination just to increase the test count.

What do we actually test in production?

My recommendation is:

Test behaviour and business rules, not every line of code.

For our current User model, I’d consider these the important behaviours:

BehaviourShould we test?Reason
Email presenceYesBusiness requirement
Email normalizationYesData consistency
Case-insensitive uniquenessYesBusiness requirement
Password authenticationYesSecurity-critical
Incorrect passwordYesSecurity-critical
Password hashingYesSecurity-critical
Password confirmationIf enabledRegistration requirement
Every possible email formatNot necessarilyAvoid redundant tests
Every possible password stringNoTest meaningful boundaries

Notice that we don’t necessarily need a separate example for every assertion. For example, password hashing could be tested in one example:

  1. Create a user.
  2. Reload the user from the database.
  3. Verify that the password digest exists.
  4. Verify that the original password isn’t stored as the password attribute.
  5. Verify that authentication still works.

That’s one meaningful behaviour test rather than several fragmented tests.

How do we decide whether to write a separate test?

I generally follow these principles.

Rule 1: Different behaviour deserves different examples.

For example:

  • Correct password authenticates.
  • Incorrect password doesn’t authenticate.

These should be separate examples because they represent different outcomes.

Rule 2: Don’t test every framework feature.

For example, Rails already implements has_secure_password. We don’t need to test every internal operation of bcrypt. We need to test that our application uses it correctly.

Rule 3: Test security boundaries thoroughly.

Authentication, authorization, permissions, data ownership and input validation deserve more attention than simple getters and setters.

Rule 4: Test regressions.

Suppose a developer changes email normalization and accidentally removes .downcase. A good test should catch that regression.

Regression testing is a type of software testing performed to ensure that a recent code change, bug fix, new feature, or system update has not broken existing functionality.

When is it Performed?

  • You typically trigger regression testing in situations such as:
  • After bug fixes: To confirm that fixing one issue did not inadvertently create another.
  • After adding new features: To make sure new code plays nicely with legacy code.
  • After code refactoring: When the underlying code is cleaned up or restructured without changing its external behavior.
  • Before a major release: As a final baseline check across critical user journeys

What happens when a model becomes bigger?

Imagine our User model eventually supports:

class User < ApplicationRecord
  has_secure_password

  has_many :tasks
  has_many :refresh_sessions

  # Email normalization
  # Password validations
  # Account status
  # Roles
  # Account locking
  # Email verification
end

We shouldn’t put every possible test into one enormous example group.

We organize them by behaviour:

spec/
└── models/
    └── user_spec.rb

Inside:

RSpec.describe User, type: :model do
  describe "validations" do
    # Relevant validation examples
  end

  describe "associations" do
    # Association behaviour
  end

  describe "authentication" do
    # Password authentication
  end

  describe "email normalization" do
    # Normalization behaviour
  end

  describe "account locking" do
    # Account locking behaviour
  end
end

If the model becomes excessively complex, we should also consider extracting responsibilities into service objects or dedicated domain components instead of continuing to grow the model indefinitely.

What about 100% test coverage?

Don’t chase 100% coverage blindly.

Consider:

  • 100% line coverage doesn’t guarantee that your application works correctly.
  • A test can execute a line without checking its result.
  • Critical security behaviour deserves tests even if the overall coverage is already high.

I prefer meaningful test coverage over a high coverage percentage.

My recommendation for our project

We’ll follow a practical testing strategy.

Our testing strategy

Model specs: Validate business rules, model behaviour, associations and important edge cases.

Request specs: Test HTTP requests, authentication, authorization, status codes and JSON responses.

Service specs: Test independent business logic such as JWT generation, verification and refresh-token rotation.

Integration testing: Verify that important application workflows work together.

Introduce FactoryBot

Let’s introduce FactoryBot, one of the most commonly used tools in Rails testing. Our goal is to stop manually constructing User records in every RSpec example and create reusable test data instead.

FactoryBot setup and fundamentals

1. Why do we need FactoryBot?

Consider our existing RSpec code:

let(:valid_user) do
  User.create!(
    email: "email@example.com",
    password: "password@1"
  )
end

Imagine we have 50 test examples involving users. We might repeatedly write: User.create!(email: "...", password: "...")

This creates several problems:

  • Repeated test data.
  • Duplicate attribute definitions.
  • Difficulties maintaining tests when models evolve.
  • Unintentional duplicate email addresses.
  • Complex setup when models have associations.

FactoryBot solves this by allowing us to define reusable object blueprints called factories.

Install FactoryBot:

Official Gem Repo: https://github.com/thoughtbot/factory_bot_rails

Open backend/Gemfile. Add:

group :development, :test do
  gem "factory_bot_rails"
end

Why both groups?

  • test: We need FactoryBot to create test data.
  • development: Enables Rails generator integration, so Rails can generate factories when we generate models.

Do: bundle install

Configure FactoryBot with RSpec

We want to use: build(:user)
create(:user)

Instead of writing: FactoryBot.build(:user)
FactoryBot.create(:user)

Both are valid. We’ll enable the shorter syntax in RSpec. Create a support directory:

mkdir -p spec/support
touch spec/support/factory_bot.rb

In spec/support/factory_bot.rb, add this configuration:

RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
end

Now open: spec/rails_helper.rb

Find this line (it may be commented out):

# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }

Uncomment it. See the comment above. This ensures that our support files are loaded when RSpec starts. This is fine for us as we only load the Rspec configuration from the support folder.

Why use spec/support?

As our testing infrastructure grows, we’ll add reusable configuration and helpers here.

For example:

spec/
├── factories/
├── models/
├── requests/
├── services/
├── support/
│   └── factory_bot.rb
├── rails_helper.rb
└── spec_helper.rb

Create your first factory

Create the file: mkdir -p spec/factories
touch spec/factories/users.rb

Our first factory will represent a valid User. The structure will look like this:

FactoryBot.define do
  factory :user do
    sequence(:email) { |n| "user#{n}@example.com" }

    password { "password@1" }
  end
end

Let’s understand each part.

FactoryBot.define – Container for our factory definitions.

factory :user – Defines a factory named user.

FactoryBot automatically identifies the corresponding Rails model as User.

sequence(:email) – Generates a unique email each time the factory is evaluated.

For example:

user1@example.com
user2@example.com
user3@example.com

Why do we need sequences?

Remember our unique email constraint in PostgreSQL. Without sequences, creating multiple users with the same email could result in uniqueness validation errors.

password – Provides a default password that satisfies our current User model requirements.

One important practice: a factory should provide the minimum attributes necessary to create a valid object. We’ll introduce optional attributes and traits later.

Understand FactoryBot build strategies

This is probably the most important FactoryBot concept.

FactoryBot supports four commonly used strategies.

1. build(:user)

In memory user = build(:user)

  • Creates a User instance.
  • Does not save it to PostgreSQL.
  • Does not execute database persistence callbacks.
  • Returns an unsaved ActiveRecord object.

Equivalent in concept to: User.new(...)

Use when: Testing validations and model behaviour without requiring database persistence.

2. create(:user)

Persisted user = create(:user)

  • Builds a User instance.
  • Saves it to PostgreSQL.
  • Runs validations and persistence callbacks.
  • Returns a persisted record.

Equivalent in concept to: User.create!(...)

Use when: Testing uniqueness, database queries, associations and persistence-related behaviour.

3. build_stubbed(:user)

Stubbed object user = build_stubbed(:user)

  • Does not save the record to PostgreSQL.
  • Assigns simulated persistence attributes such as an ID.
  • Stubs database-related behaviour.

Use when: You need an object that behaves like a persisted record but don’t need actual database interaction.

Be careful: it isn’t a substitute for a real persisted record in integration or database-dependent tests.

4. attributes_for(:user)

Hash only attributes = attributes_for(:user)

Returns an attribute hash rather than a User object.

Use when: Building request payloads or testing API input handling.

An important performance consideration: unnecessary database writes make large test suites slower. Choose the lightest strategy that actually tests the behaviour you care about.

FactoryBot traits and list factories

Now let’s learn two features that become particularly useful when application models grow.

1. List factories: build_list and create_list

Suppose we need five users for a test.

Without list factories:

user1 = create(:user)
user2 = create(:user)
user3 = create(:user)
user4 = create(:user)
user5 = create(:user)

FactoryBot provides a better way.

build_list – users = build_list(:user, 5) – Creates five User objects without saving them.

create_list – users = create_list(:user, 5) – Creates five User records and persists them to PostgreSQL.

MethodObjectsDatabase
build_list5No records
create_list55 records

Both methods return arrays.

Exercise

Create a new spec: touch spec/learning/factory_bot_lists_spec.rb Write two examples.

Exercise A – build_list – Create three users and verify:

  • Array contains three users.
  • None of the users is persisted.
  • All three emails are unique.

Exercise B – create_list – Create three users and verify:

  • Array contains three users.
  • All three are persisted.
  • All three have unique IDs
describe "Factory Bot: Build list" do
    context "create three users and verify" do
      it "contains 3 users" do
        users = build_list(:user, 3)
        expect(users.size).to eq(3)
      end
      it "3 users are not persisted and emails are unique" do
        users = build_list(:user, 3)
        emails = []
        users.each do |user|
          emails << user.email
          expect(user.persisted?).to eq(false)
        end
        expect(emails.uniq.size).to eq(3)
      end
    end
  end

  describe "Factory Bot: Create list" do
    context "create three users and verify" do
      it "contains 3 users" do
        users = create_list(:user, 3)
        expect(users.size).to eq(3)
      end
      it "all users are persisted and have unique ids" do
        users = create_list(:user, 3)
        user_ids = []
        users.each do |user|
          user_ids << user.id
          expect(user.persisted?).to eq(true)
        end
        expect(user_ids.uniq.size).to eq(3)
      end
    end
  end

FactoryBot traits

Now imagine our User model supports password confirmation. We may need different user states in different tests:

  • User with matching password confirmation.
  • User with mismatched password confirmation.
  • User without password.

We don’t want to create a separate factory for every scenario. This is where traits are useful. A trait represents a reusable variation of an existing factory. For example:

build(:user, :with_password_confirmation) Or: build(:user, :with_invalid_password_confirmation)

Both reuse the same :user factory but apply different attributes.

Assignment

Open: spec/factories/users.rb Add two traits:

TraitBehaviour
:with_password_confirmationSets password confirmation equal to password
:with_invalid_password_confirmationSets a different password confirmation

Don’t add any new model validations. Rails’ has_secure_password already supports password confirmation validation when confirmation is supplied.

Test these traits

In your new spec file, create examples that:

  1. Build a user with matching password confirmation and verify that it is valid.
  2. Build a user with mismatched password confirmation and verify that it is invalid.
  3. Verify that the second user has the expected validation error.

Important: Use build, not create for these tests. We are testing validation behaviour, not database persistence.

# spec/models/user_spec.rb

context "With Traits" do
      it "verify with password confirmation" do
        user = build(:user, :with_password_confirmation)
        expect(user.valid?).to eq(true)
      end
      it "verify with invalid password confirmation" do
        user = build(:user, :with_invalid_password_confirmation)
        expect(user.valid?).to eq(false)
        expect(user.errors.full_messages).to include("Password confirmation doesn't match Password")
      end
    end

Understanding when to use traits vs overrides

This distinction is useful in real projects.

RequirementPreferred approach
Change email for one exampleAttribute override
Create multiple userscreate_list
Reuse an admin user stateTrait
Reuse an inactive user stateTrait
Change password for one exampleAttribute override
Reuse a specific authentication stateTrait

Don’t create traits for every possible attribute combination. Traits are most useful for meaningful, reusable object states.

Create the Task model and database relationship

Now we’re moving into the actual Task Management application.

Our first important domain relationship:

  • One User can create multiple Tasks.
  • Every Task belongs to exactly one User.

Database relationship

User 1 : N Tasks -> user_id (FK) – Each task stores the ID of its owner.

1. Decide our Task attributes

Let’s start with a simple schema.

ColumnTypeConfiguration
idbigintPrimary key
user_idbigintForeign key, NOT NULL
titlestringNOT NULL
descriptiontextNullable
statusintegerNOT NULL, default 0
created_atdatetimeAutomatically generated
updated_atdatetimeAutomatically generated

For the status, we’ll eventually support:

  • pending
  • in_progress
  • completed

Why integer?

Rails supports enums that map readable status names to integer values in the database. We’ll implement the enum separately and understand its advantages and pitfalls, particularly why explicitly mapping enum values is important.

Generate the Task model

From your backend directory:

bin/rails generate model Task title:string description:text status:integer user:references

Because we’ve configured RSpec generators, you should get (notice invoking Rspec and FactoryBot):

Inspect the actual migration and make the necessary adjustments.

Configure the associations

Open: app/models/user.rb – Add the one-to-many association.
Open: app/models/task.rb – Inspect the generated belongs_to association.

# migration
class CreateTasks < ActiveRecord::Migration[8.1]
  def change
    create_table :tasks do |t|
      t.string :title, null: false
      t.text :description
      t.integer :status, null: false, default: 0
      t.references :user, null: false, foreign_key: true

      t.timestamps
    end
  end
end

# user model
class User
  has_many :tasks, dependant: :destroy
  ....
end

# task model
class Task < ApplicationRecord
  belongs_to :user
end
 

We’ll discuss the difference between destroy, delete, dependent: :delete_all and database-level cascading deletion later.

Do: rails db:migrate -t, check database table details:

FactoryBot associations: User and Task

This is particularly useful because real applications rarely have isolated models. Most models have relationships, and our tests need to create related records efficiently.

1. Create the Task factory

Open: spec/factories/tasks.rb

Our Task model has:

  • title
  • description
  • status
  • user_id

We want every generated Task to have an associated User. Your factory should follow this structure:

FactoryBot.define do
  factory :task do
    title { "Improve Product" }
    description { "Improve the product page by minimizing dependancies" }

    association :user
  end
end

Understand association :user

FactoryBot understands that the Task factory needs a User factory to construct its associated User. It automatically resolves the :user factory. You could also write: user. But I prefer association :user for now.

How does FactoryBot handle associated objects?

This is an important concept. FactoryBot uses the parent’s build strategy for associations by default.

Consider: task = build(:task)

Expected behaviour:

build(:task)
     |
     v
Build Task object
     |
     v
Build associated User
     |
     v
Return Task
     |
     v
Neither record persisted

Now consider: task = create(:task)

Expected behaviour:

create(:task)
     |
     v
Create associated User
     |
     v
Create Task with user_id
     |
     v
Both records persisted

This is controlled by FactoryBot’s use_parent_strategy configuration, which defaults to true

An important mistake to avoid:

Don’t write this inside the Task factory: user { create(:user) }

Why? Even when you call build(:task), this explicitly creates and persists the User. You lose the advantage of build. Use association :user instead.

Attribute override for associations

Let’s say we already have a User and want to assign that specific User to a Task.

We can override the association:

user = create(:user)

task = build(:task, user: user)

Now the Task belongs to the User you supplied. This is useful when testing ownership, permissions and authorization later. For example, we’ll eventually have multiple users, each with their own tasks.

RSpec assignment

open: backend/spec/models/task_spec.rb

Use:

RSpec.describe Task, type: :model do
  describe "associations" do
    it "belongs_to" do
      task = create(:task)
      expect(task.user).to be_truthy
      expect(task.user_id).to be_truthy
    end
    it "has_many" do
      user = create(:user)
      create_list(:task, 3, user: user)

      expect(user.tasks.count).to eq(3)
    end
  end
end

Implement these four examples.

Exercise 1 – Build associated User

Use build(:task). Verify:

  • Task is not persisted.
  • Task has a User object.
  • Associated User is not persisted.

Exercise 2 – Create associated User

Use create(:task). Verify:

  • Task is persisted.
  • Associated User is persisted.
  • task.user_id matches task.user.id.

Exercise 3 – Override association

Create a User separately. Pass that User into build(:task, user: user). Verify that the Task belongs to the exact User object supplied.
Hint: Think about the difference between eq and equal.

Exercise 4 – Multiple Tasks for one User

Create one User and three Tasks associated with that User. Verify:

  • There are three Tasks.
  • All three belong to the same User.
  • All three Tasks are associated with the User through the has_many relationship.
    • Hint: create_list(:task, 3, user: user).

Run your tests: rspec spec/models/task_spec.rb --format documentation

If your test database hasn’t been prepared since the Task migration: You could use bin/rails db:test:prepare

Task model validations

Now let’s implement actual business rules for our Task model.

1. Define our validation requirements

For our application, let’s establish these rules:

AttributeRequirement
titleRequired
titleMaximum 120 characters
descriptionOptional
descriptionMaximum 2,000 characters
userRequired
statusWe’ll handle separately using Rails enums

Why these requirements?

  • A task without a title doesn’t provide meaningful information.
  • A title should be reasonably short because it appears in the task list.
  • Description should be optional because sometimes users only need a task title.
  • Every task must belong to a user.

Rails automatically validates the presence of the associated user by default. You generally don’t need to add another validates :user, presence: true. Remember that we also have a database foreign key and NOT NULL constraint. These protect the database independently of model validations.

class Task < ApplicationRecord
  belongs_to :user

  validates :title, presence: true, length: { maximum: 120 }
  validates :description, length: { maximum: 2000 }, allow_blank: true
end

Write Task model specs

Open: backend/spec/models/task_spec.rb

Organize the tests using:

RSpec.describe Task, type: :model do
  describe "validations" do
    it "a valid task" do
      task = build(:task)
      expect(task.valid?).to eq(true)
    end

    it "title presence, check nil, empty, space contents" do
      task = build(:task, title: nil)
      task.valid?
      expect(task.errors.full_messages).to include("Title can't be blank")
      task = build(:task, title: '')
      task.valid?
      expect(task.errors.full_messages).to include("Title can't be blank")
      expect(task.errors.full_messages).to include("Title is too short (minimum is 2 characters)")
      task = build(:task, title: '  ')
      task.valid?
      expect(task.errors.full_messages).to include("Title can't be blank")
    end
    
    it "title length" do
      task = build(:task, title: "my " * 40) # 120 chars
      expect(task.valid?).to eq(true)
      task = build(:task, title: "my " * 40 + "q") # 121 chars
      expect(task.valid?).to eq(false)
    end
    
    it "valid description" do
      task = build(:task, description: nil)
      expect(task.valid?).to eq(true)
      task = build(:task, description: "my" * 1000) # 2000 chars
      expect(task.valid?).to eq(true)
      task = build(:task, description: "my" * 1000 + 'm') # 2001 chars
      expect(task.valid?).to eq(false)
    end
    
    it "user association" do
      task = build(:task, user: nil)
      expect(task.valid?).to eq(false)
    end
  end
end

Use FactoryBot for test data.

Exercise 1 – Valid task
Exercise 2 – Title presence – Title is nil. Title is an empty string.
Exercise 3 – Title length
Exercise 4 – Description – Description is nil – valid. Description is empty – valid.

Exercise 1 – User has many tasks – Create a user and three associated tasks. Verify that:

  • The user has three tasks.
  • All tasks belong to that user.
  • All returned tasks are persisted.

Exercise 2 – Destroy dependent tasks – Create a user and three associated tasks. Destroy the user. Verify:

  • The user is destroyed.
  • All three tasks are destroyed.
  • The task records no longer exist in the database.

Hint: You can use reload carefully or Task.exists? to verify database state.

Exercise 3 – Task belongs to User – Create a task. Verify:

  • task.user returns a User.
  • task.user_id matches task.user.id.
  • The association can be reloaded successfully.



Let’s move to an important Rails feature: ActiveRecord Enums.

task.user returns a User.

task.user_id matches task.user.id.

Rails Enums

We’ll implement task statuses using Rails enums and learn how Rails maps human-readable values to integers in PostgreSQL.

1. Why do we need enums?

Our Task model has a status integer column. Without enums, we might write:

task.status = 0 # Pending
task.status = 1 # In progress
task.status = 2 # Completed


What’s the problem? Imagine another developer reads this:

if task.status == 2
end

What does 2 mean? We need readable values instead. Rails enums solve this problem.

Define our Task statuses

We’ll support three statuses:

Pending 0 – Task hasn’t been started yet.

In progress 1 – Task is currently being worked on.

Completed 2 – Task has been completed.

Open: backend/app/models/task.rb

enum :status, {
  pending: 0,
  in_progress: 1,
  completed: 2
}, validate: true

This is the Rails 8.1 enum syntax. Official documentation: ActiveRecord::Enum – Rails 8.1.4

Why use an explicit hash instead of an array?

Rails also supports: enum :status, [:pending, :in_progress, :completed]

This automatically maps values based on their positions:

pending => 0
in_progress => 1
completed => 2

However, consider adding another status in the middle later. The integer mapping could change, potentially corrupting the interpretation of existing records.

My recommendation: Always use explicit integer mappings for database-backed enums in production applications. Keep existing mappings stable.

Understand what Rails generates automatically

This is where enums become interesting. Once you define the enum, Rails generates several methods automatically.

A. Predicate methods

You can check the current status:

task.pending?
task.in_progress?
task.completed?

Example:

task = Task.new
task.status
# "pending"

task.pending?
# true

task.completed?
# false

The initial status comes from our database default of 0

Bang methods

Rails generates methods that update and persist the status:

task.in_progress!
task.completed!
task.pending!

For example:

task = Task.create!(title: "Learn Rails", user: user)

task.completed!

This updates the database. Remember: the ! methods save the record through update!. They are different from simply assigning an attribute.

Scopes

Rails automatically generates scopes:

Task.pending
Task.in_progress
Task.completed

These return ActiveRecord relations. For example: Task.pending

Conceptually generates a query similar to:

SELECT * FROM tasks WHERE status = 0;

You can also use negative scopes: Task.not_completed

These are particularly useful later when implementing the task filters in React.

Reading and updating status

You can assign a status using its symbolic value:

task.status = :completed

Or:

task.update!(status: :in_progress)

Reading the status returns its string representation:

task.status
# "in_progress"

However, the underlying database value is an integer.

Accessing the mapping

Rails also provides:

> Task.statuses
=> {"pending" => 0, "in_progress" => 1, "completed" => 2}

Useful when you need to inspect the database mapping or build queries.

Important: What does validate: true do?

Notice that we used: validate: true This is an important option. By default, assigning an unsupported enum value raises an ArgumentError immediately.

For example:

task.status = :unknown

But with validate: true:

task.status = :unknown

task.valid?
# false

Rails adds an inclusion validation instead.

Why did we choose this?

Eventually, our React application will send status values to Rails through API requests. Suppose React sends:

{
  "status": "invalid_status"
}

We want to handle this as a model validation failure and return a proper 422 Unprocessable Entity response, rather than accidentally returning a server error because of an exception.

This is a deliberate choice for our API. Rails documents both behaviours. Check: https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Enum.html

RSpec assignment

Now let’s test the actual enum functionality. Open: backend/spec/models/task_spec.rb

Add a new group:

describe "status" do
    it "default status" do
      task = build(:task)
      expect(task.status).to eq('pending')
      expect(task.pending?).to eq(true)
      expect(task.completed?).to eq(false)
    end

    it "status assignment" do
      task = build(:task, status: :in_progress)
      expect(task.status).to eq('in_progress')
      expect(task.in_progress?).to eq(true)
      expect(task.pending?).to eq(false)
    end

    it "status bang methods" do
      task = create(:task)
      task.completed!
      expect(task.status).to eq('completed')
      expect(task.completed?).to eq(true)
      expect(task.pending?).to eq(false)
      task.reload # confirm db persistence
      expect(task.completed?).to eq(true)
    end

    it "Enum mapping" do
      status = described_class.statuses
      expect(status['pending']).to eq(0)
      expect(status['in_progress']).to eq(1)
      expect(status['completed']).to eq(2)
    end

    it "Invalid status" do
      task = build(:task)
      task.status = :invalid
      expect(task.valid?).to eq(false)
      not_included_msg = "Status is not included in the list"
      expect(task.errors.full_messages).to include(not_included_msg)
      task.status = nil
      task.valid?
      expect(task.errors.full_messages).to include(not_included_msg)
    end

    it "Enum scopes" do
      pending = create(:task)
      in_progress = create(:task, status: :in_progress)
      completed = create(:task, status: :completed)
      expect(Task.pending).to contain_exactly(pending)
      expect(Task.in_progress).to contain_exactly(in_progress)
      expect(Task.completed).to contain_exactly(completed)
    end
  end

Implement these six scenarios.

Exercise 1 – Default status

Build a new Task without specifying its status. Verify:

  • task.status returns "pending".
  • task.pending? returns true.
  • task.completed? returns false.

Remember, this depends on the database default being 0.

Exercise 2 – Status assignment

Build a Task with: status: :in_progress Verify:

  • Its status is "in_progress".
  • in_progress? returns true.
  • pending? returns false.

Exercise 3 – Bang methods

Create a persisted Task and call: task.completed! Verify:

  • completed? returns true.
  • The updated status is "completed".
  • Reloading the record still gives "completed".

Why do we reload? We want to verify that the database was actually updated.

Exercise 4 – Enum mapping

Verify the mapping returned by: described_class.statuses

Check that each status maps to the expected integer.

Exercise 5 – Invalid status

Build a Task and assign: task.status = :invalid_status

Because we enabled validate: true, verify that:

  • No ArgumentError is raised.
  • task.valid? returns false.
  • A status validation error is present.

Also check what happens when status is explicitly assigned nil.

Exercise 6 – Enum scopes

Create three Tasks:

  • One pending.
  • One in progress.
  • One completed.

Verify that:

Task.pending
Task.in_progress
Task.completed

each returns only the matching Task. Use contain_exactly or match_array where appropriate.

One database configuration check

Before running the tests, inspect your original Task migration and schema.rb. We should have: t.integer "status", default: 0, null: false

This is important for two reasons:

  • Every new task starts as pending.
  • The database doesn’t allow a NULL status.

If you already configured this earlier, no changes are necessary. If the migration has already been applied and the constraint is missing, generate a new migration rather than silently changing an already-applied migration.

Q) Why do you use Enums? and integer-backed enums instead of storing strings directly?

Rails enums provide a convenient interface for managing a fixed set of values, including generated predicate methods, scopes and update methods. Integer-backed enums also use less storage and generally produce more compact indexes than string-backed equivalents.

However, string-backed enums are also supported. The choice depends on database readability, maintainability and performance requirements. I wouldn’t choose integer-backed enums solely for performance without measuring the actual workload.

We shouldn’t use integers just because Rails supports enums.

You can absolutely store "pending", "in_progress" and "completed" directly as strings in PostgreSQL. There are legitimate reasons to choose either approach.

Let’s understand the actual trade-offs.

1. Three ways to store status

There are three approaches worth understanding.

Option A: Store strings directly

Database:

tasks
--------------------------------
id | title       | status
--------------------------------
1  | Learn Rails | pending
2  | Learn React | in_progress
3  | Write tests | completed

Migration: t.string :status, default: "pending", null: false

You can query directly: Task.where(status: "pending")

But you need to implement your own validation:

validates :status, inclusion: {
in: %w[pending in_progress completed]
}

And implement any convenience methods or scopes yourself.

Advantages:

  • Database values are human-readable.
  • Easy to inspect using SQL.
  • No integer mapping to maintain.
  • Adding a new status is straightforward.

Option B: Rails integer-backed enum

This is what we’re currently implementing.

Database:

tasks
--------------------------------
id | title       | status
--------------------------------
1  | Learn Rails | 0
2  | Learn React | 1
3  | Write tests | 2

Rails model:

enum :status, {
  pending: 0,
  in_progress: 1,
  completed: 2
}, validate: true

Rails translates between the integer and its corresponding symbolic value.

For example:

task.status
# "pending"

task.status = :completed

task.save!

task.status
# "completed"

You also get:

task.pending?
task.completed!

Task.pending
Task.completed

These methods and scopes are generated by Rails.

Option C: Rails string-backed enum

Here’s something interesting: you can use Rails enum functionality without storing integers!

enum :status, {
  pending: "pending",
  in_progress: "in_progress",
  completed: "completed"
}, validate: true

Your database column must be a string. Now you get the same convenience methods:

task.pending?
task.completed!

Task.pending
Task.completed

But PostgreSQL stores the actual strings.

Rails supports both integer-backed and string-backed enums. Its documentation notes that string-backed enums will likely result in slower database queries.

2. Does storing integers improve performance?

Yes, there can be storage and indexing advantages. But let’s understand how significant they are.

A. Storage size

PostgreSQL uses:

For our three statuses:

StatusString lengthApprox. PostgreSQL storage
pending7 bytes8 bytes
completed9 bytes10 bytes
in_progress11 bytes12 bytes
Integer mapping4 bytes4 bytes

Approximate column value storage, excluding row and index overhead.

Imagine you have 10 million tasks.

For illustration, assuming every record has the same status:

StorageApproximate size
Integer (4 bytes)38.1 MiB
String pending (8 bytes)76.3 MiB

That difference becomes meaningful at scale. For our small Task Management application, however, the difference is practically irrelevant.

B. Index performance

This is where your question becomes interesting. Suppose we create an index:

add_index :tasks, :status

With an integer-backed enum, the database indexes integer values.

With a string-backed enum, the database indexes string values.

Both can use PostgreSQL B-tree indexes.

Integer index keys are more compact and integer comparisons are generally cheaper than string comparisons. However, don’t assume that integer storage automatically makes every query faster.

Consider: SELECT * FROM tasks WHERE status = 0;

versus: SELECT * FROM tasks WHERE status = 'pending';

Both can use an appropriate index.

An important point: Our status column has only three possible values. This is called low cardinality.

If 60% of your records are pending, an index on status alone might not be particularly useful. PostgreSQL may prefer a sequential scan because so many rows match.

We need to consider actual queries and their execution plans. For our application, a query such as: Task.where(user_id: current_user.id, status: :pending)

might benefit from a composite index: add_index :tasks, [:user_id, :status]

We shouldn’t add it blindly, though. We’ll later examine EXPLAIN ANALYZE and understand whether it helps.

3. What is the actual benefit of Rails enums?

In my opinion, this is the more important reason to use them. Regardless of whether you choose integer or string storage, Rails enums provide a convenient interface for working with a fixed set of values.

Without enums, you might write:

task.status == "completed"

Task.where(status: "pending")

And define your own scopes and methods.

With Rails enums:

task.completed?

task.completed!

Task.pending
Task.in_progress
Task.completed

You also get the status mapping through: Task.statuses

So enums provide:

  1. A defined set of allowed values.
  2. Generated predicate methods.
  3. Generated update methods.
  4. Generated database query scopes.
  5. Consistent mapping between application values and stored values.

This is why enums are useful even when storage performance isn’t important.

One distinction: a Rails enum is not the same thing as PostgreSQL’s native ENUM data type. Rails’ integer-backed enum is an application-level mapping to a normal integer column.

4. What would I choose for our Task Management application?

Here’s the recommendation.

ConsiderationInteger-backedString-backed
Storage efficiencyBetterSlightly larger
Index key sizeSmallerLarger
Database readabilityLess readableMore readable
Rails generated methodsYesYes
Adding statusesMaintain mappingsMore straightforward
SQL debuggingRequires mappingDirectly readable

For our project, both are perfectly reasonable.

I would actually lean towards string-backed Rails enums for this particular application if we were prioritizing database readability and simplicity over storage optimization.

We only have three statuses, and there’s no meaningful performance bottleneck here.

However, we’ll retain the integer-backed implementation for our current exercise so you understand the conventional Rails approach, its generated methods, its mapping and its trade-offs.

One takeaway for our project: Enums are primarily about representing and managing a fixed set of domain values conveniently. Integer storage is an additional benefit, not the fundamental reason to use enums.

Implement Task Manager application with Ruby on Rails backend, React frontend, Postgresql, Rspec, Docker and Github Actions

Let’s create an application for managing Tasks that are created by different users. Let’s use React UI for quick data response. The app consists of CRUD operations of Tasks, User Authentication using JWT-Tokens, User Authorization for their particular tasks.

Technology stack

Here’s the list of technology stack we use in our application.

LayerTechnologyPurpose
BackendRuby on Rails 8.1+REST API
DatabasePostgreSQLPersistent storage
FrontendReactUI
LanguageTypeScriptStatic typing
Build toolViteFrontend development/build
UI libraryFluent UI React v9Components and styling
HTTPFetch API initiallyAPI communication
Server cacheTanStack QueryAPI data caching
Global stateRedux ToolkitShared client-side state
Testing backendRSpecAPI and model tests
Testing frontendVitest + React Testing LibraryComponent tests
ContainersDocker + Docker ComposeContainerization
CI/CDGitHub ActionsAutomation and deployment

Check our ruby current version.

$ ruby -v

ruby 3.4.1 (2024-12-25 revision 48d4efcb85)

Check the security patches and updates of our version.

https://www.ruby-lang.org/en/downloads/releases

Then update the latest compatible version.

$ mise use -g ruby@3.4.12

(2026-10-23 revision 366f5fdc00)

To uninstall Ruby using mise, run mise uninstall ruby@ to delete a specific installed version.

$ mise uninstall ruby@3.4.1

Install latest ruby version that you need.

Switch between versions globally:

$ mise use -g ruby@3.4.12

$ mise use -g ruby@4.0.9

Check all needed versions exists:

ruby -v
gem -v
rails -v
node -v
npm -v
psql --version

Check Postgres versions available here: https://www.postgresql.org/download/macosx/

Download the one of the latest one if you have currently installed the old version.

$ brew install postgresql@18

Installing postgresql@18
==> Pouring postgresql@18--18.7.arm64_tahoe.bottle.tar.gz
Warning: postgresql@18 was installed but not linked because postgresql@14 is already linked.
To link this version, run:
brew link postgresql@18

$ brew link postgresql@18
Unlinking /opt/homebrew/Cellar/postgresql@14/14.17_1... 2165 symlinks removed.
Linking /opt/homebrew/Cellar/postgresql@18/18.7... 812 symlinks created.
$ psql --version
psql (PostgreSQL) 18.7 (Homebrew)

Update node js:

$ node -v
v24.14.0

install the latest Long-Term Support release

$ nvm install --lts
Installing latest LTS version.
Downloading and installing node v26.13.1...
Downloading https://nodejs.org/dist/v26.13.1/node-v26.13.1-darwin-arm64.tar.xz...
Computing checksum with sha256sum
Checksums matched!
Now using node v26.13.1 (npm v11.20.0)

Create app folder:

$ mkdir rails-react-task-manager
$ cd rails-react-task-manager
$ git init -b main

We want to manage the backend, frontend, Docker configuration and CI/CD workflows in one repository.

Update ruby gems:

A new release of RubyGems is available: 4.0.20 → 4.0.24!
See https://github.com/ruby/rubygems/blob/v4.0.24/CHANGELOG.md for the changes since 4.0.20.
Run `gem update --system 4.0.24` to update your installation

Install Rails:

check rails newest versions: https://rubygems.org/gems/rails/versions

$ gem install rails -v '~> 8.1.0'

Note: Pessimistic version constraint. Using -v “~> 8.1.0” installs the latest patch release within the 8.1 series (such as 8.1.4.1) while avoiding unintended jumps to future minor or major versions

Reopen the shell and check:

Create a github repository

name it: rails-react-task-manager

$ git remote add origin git@github.com:<username>/rails-react-task-manager.git

Problem 1:

The first problem I faced was the command rails new already has the folders: .git, .github, .gitattributes, .gitignore etc inside rails app.

So when I try to push the rails app:

git add backend/
error: 'backend/' does not have a commit checked out
error: unable to index file 'backend/'
fatal: adding files failed

This happens because Rails automatically initializes a Git repository when you run rails new.

Solution: Keep only one Git repository

Since we’re building a monorepo, we want Git initialized only at the project root.

Remove only the nested Git metadata:

rm -rf backend/.git
TypeWhen to Use It Example
choreUpgrading packages, libraries, or runtime versions chore: update Node.js version or chore(deps): bump lodash
featAdding a new feature or capability for the user.feat: add user login via OAuth
fixPatching a bug in the application code.fix: resolve crash on checkout page
refactorRestructuring production code without changing its behavior.refactor: simplify auth helper logic
docsUpdating READMEs, comments, or API guides.docs: add setup instructions
styleFixing formatting, whitespace, or missing semicolons.style: format files with Prettier
testAdding or updating unit and integration tests.test: add unit tests for cart total
build / ciMaking dedicated changes to build systems or CI pipelines (used by teams that prefer stricter categories over chore).ci: cache node_modules in pipeline

Problem 2:

Accessing the Rails url at: http://localhost:3000/

Started GET "/" for ::1 at 2026-11-15 

ActiveRecord::StatementInvalid (PG::InvalidParameterValue: ERROR:  invalid value for parameter "TimeZone": "UTC"
)
Caused by: PG::InvalidParameterValue (ERROR:  invalid value for parameter "TimeZone": "UTC"
)

Information for: ActiveRecord::StatementInvalid (PG::InvalidParameterValue: ERROR:  invalid value for parameter "TimeZone": "UTC"
):

Solution: check which PostgreSQL server is actually running

psql --version
brew services list
brew services stop postgresql@14
brew services restart postgresql@18
# then do
rails db:prepare -t # recommended

Restart the rails server. Also check:

curl -i http://localhost:3000/up

Install RSpec

Add RSpec to Gemfile

group :development, :test do
  gem "rspec-rails", "~> 8.1"
end

Install the gem

cd backend
bundle install
bundle exec rspec --version

Generate RSpec configuration

 rails g rspec:install
      create  .rspec
      create  spec
      create  spec/spec_helper.rb
      create  spec/rails_helper.rb
FileResponsibility
.rspecDefault command-line options for RSpec
spec_helper.rbGeneral RSpec configuration
rails_helper.rbRails-specific test configuration

Important distinction:

spec_helper.rb can be used for tests that don’t require Rails.

rails_helper.rb loads the Rails application and integrates Rails testing functionality.

Verify:

bundle exec rspec
No examples found.

Finished in 0.00022 seconds (files took 0.05449 seconds to load)
0 examples, 0 failures

Minitest is still present: Your Rails application probably already has: backend/test/. That’s because Rails generated its default Minitest structure. We’ll configure Rails generators to use RSpec automatically, so that when we generate a model, Rails creates: spec/models/task_spec.rb instead of: test/models/task_test.rb. We’ll also decide how to handle the existing Minitest files cleanly.

Configure Rails generators to use RSpec

Currently, Rails uses Minitest as its default testing framework. For example, when you generate a model: bin/rails generate model Task title:string, Rails normally generates: app/models/task.rb
test/models/task_test.rb

But we want: app/models/task.rb
spec/models/task_spec.rb

RSpec Rails integrates with Rails generators to do exactly this.

Open: backend/config/application.rb and add:

config.generators do |g|
  g.test_framework :rspec
end

Important: This does not remove Minitest or disable its test runner. It changes the default generator behaviour.

We don’t want to generate our actual Task model just to test the configuration.

Instead, use Rails --pretend option:

rails g model Task title:string --pretend
      invoke  active_record
      create    db/migrate/20261115171837_create_tasks.rb
      create    app/models/task.rb
      invoke    rspec
      create      spec/models/task_spec.rb

Rspec Structure:

spec/
├── models/
│   └── task_spec.rb
│
├── requests/
│   └── api/
│       └── v1/
│           └── tasks_spec.rb
│
├── services/
│   └── authentication/
│
├── jobs/
├── factories/
│
├── spec_helper.rb
└── rails_helper.rb

For our Rails API, we’ll primarily use request specs instead of controller specs. A request spec tests the application from the HTTP client’s perspective. This lets us test the complete API behaviour rather than testing controller methods in isolation. RSpec Rails recommends request specs as the higher-level alternative to controller specs.

For example:

HTTP Request
    ↓
Router
    ↓
Controller
    ↓
Authentication
    ↓
Authorization
    ↓
Model / Database
    ↓
HTTP Response

Understand the structure of an RSpec test

An RSpec test typically consists of four important building blocks:

RSpec syntaxPurpose
RSpec.describeDefines the top-level example group
describeGroups related examples
contextDescribes a particular condition or scenario
itDefines an individual test example
expectDefines an expectation
toSpecifies the expected matcher

Let’s look at a simple example.

RSpec.describe "RSpec basics" do
  describe "equality matcher" do
    it "compares two values" do
      result = 2 + 3

      expect(result).to eq(5)
    end
  end
end

Understand each line

RSpec.describe "RSpec basics" – Creates an example group. This is the outermost container for our tests.

describe "equality matcher" – Groups tests related to equality. You can nest multiple describe blocks to organize tests logically.

it "compares two values" – Defines an individual test example. The string describes the expected behaviour. RSpec uses it when displaying test results.

expect(result).to eq(5) – This is the actual expectation.

  • expect(result) – the actual value.
  • to – tells RSpec we’re checking a positive expectation.
  • eq(5) – matcher checking whether the actual value equals 5 using Ruby’s == operator.

If the expectation fails, RSpec reports a failure with the actual and expected values.

Understand RSpec matchers

Matchers are one of the most important parts of RSpec.

They determine how RSpec compares actual and expected values.

Here are some commonly used matchers:

MatcherPurposeExample
eqValue equality (==)eq(10)
beObject identity (equal?)be(true)
includeCollection contains valueinclude("Rails")
be_nilChecks nilbe_nil
be_emptyChecks empty collectionbe_empty
be_truthyChecks truthinessbe_truthy
be_falseyChecks falsinessbe_falsey
matchRegular expression matchingmatch(/rails/i)
raise_errorChecks raised exceptionraise_error(ArgumentError)

A particularly important distinction: expect("Rails").to eq("Rails")

This checks value equality. Whereas: expect(object).to be(other_object)

This checks whether both references point to the same object. Don’t confuse eq and be. You can also write negative expectations: expect(result).not_to eq(10) This verifies that the result isn’t equal to 10.

One principle to remember: Good tests should make the behaviour obvious, minimize duplicated setup and remain independent of one another. That’s the mindset I want you to develop while learning RSpec.

Understand describe vs context

They look similar, but they serve slightly different organizational purposes. Consider a future Task model.

RSpec.describe Task do
  describe "validations" do
    context "when title is present" do
      # Examples go here
    end

    context "when title is missing" do
      # Examples go here
    end
  end
end

Preferred convention:

  • describe: What behaviour are we testing?
  • context: Under what circumstances are we testing it?
  • it: What should happen?

Technically, describe and context create the same kind of RSpec example group. The difference is semantic and improves readability.

hands-on exercise

Let’s create a temporary learning spec. We aren’t creating the Task model or touching the database yet. From your backend directory:

mkdir spec/learning
touch spec/learning/rspec_basics_spec.rb

Start with the previous equality example. Now add your own examples to cover these requirements:

Exercise 1 – Equality

Write an example that checks whether 10 + 20 equals 30.

Exercise 2 – Collection

Given: languages = ["Ruby", "JavaScript", "Python"]

Write an expectation that verifies the array includes "Ruby".

Exercise 3 – Nil

Given a variable whose value is nil, verify that it is nil.

Exercise 4 – Boolean

Given a variable whose value is false, verify that it is exactly false.

Exercise 5 – Negative expectation

Verify that the languages array does not include "Java".

Execute your tests: bundle exec rspec spec/learning/rspec_basics_spec.rb

For more readable output: bundle exec rspec spec/learning/rspec_basics_spec.rb --format documentation , The documentation formatter displays the example descriptions and their results.

Refer:

https://rspec.info/features/3-13/rspec-expectations/built-in-matchers/equality

https://rspec.info/features/3-13/rspec-expectations/built-in-matchers/include

https://rspec.info/features/3-12/rspec-core/helper-methods/let

RSpec.describe "Rspec Basics learning" do
  describe "Equality" do
    let(:languages) { ["Ruby", "JavaScript", "Python"] }

    it "check addition" do
      expect(10 + 20).to eq(30)
    end

    it "include in the list" do
      expect(languages).to include "Ruby"
    end

    it "checks nil value" do
      nil_value = nil
      expect(nil_value).to be_nil
    end

    it "checks false value" do
      false_value = false
      true_value = true
      expect(false_value).to be false
      expect(false_value).to be_falsey
      expect(true_value).to be_truthy
      expect(true_value).to be true
    end

    it "checks negative expectation" do
      expect(languages).not_to include "Scala" 
    end
  end
end

# run
$ rspec spec/

Note:
be false vs be_falsey These are different expectations.

expect(false).to be false 
expect(false).to be_falsey
expect(nil).to be_falsey
expect(true).to be_truthy

be_truthy accepts anything other than false or nil. be false checks that the value is exactly false. be_falsey accepts either false or nil. let is lazily evaluated and memoized within an individual example.

We’ll apply these concepts to our first actual Rails model spec. No need to rush into FactoryBot yet. We should understand native RSpec first.

RSpec hooks: before, after, let and let!

This is one of the most frequently used parts of RSpec in real Rails projects. When writing model and request specs, we often need to prepare test data before executing an example.

For example:

  • Create a user before testing authentication.
  • Create a task before testing task updates.
  • Prepare some data before testing associations.
  • Clean up resources after an example.

RSpec provides hooks and helper methods for this.

before hook

RSpec.describe "Task" do
  before do
    puts "Running before hook"
  end

  it "checks something" do
    puts "Running example"
  end

  it "checks something else" do
    puts "Running another example"
  end
end

# output
Running before hook
Running example

Running before hook
Running another example

before executes before every example by default. These are equivalent:

before do
  # Setup
end

# and

before(:each) do
  # Setup
end

When do we use it?

When every example needs some common setup. For example, imagine we need a variable initialized before each test.

Imagine we have 10 test examples and every example requires the same initial setup.

# Without hooks, you might repeat:

it "example 1" do
  languages = ["Ruby", "JavaScript"]
  # Test logic
end

it "example 2" do
  languages = ["Ruby", "JavaScript"]
  # Test logic
end

# This creates unnecessary duplication. RSpec provides hooks to solve this problem.

Understand let vs before

This distinction is particularly important.

beforelet
Setup hookDefines a helper method
Executes automaticallyExecutes only when referenced
Runs before every example by defaultEvaluates once per example
Useful for setup actionsUseful for reusable test data

after hook: after executes after each example.

after(:each) do
  puts "Cleaning up"
end

Typical use cases:

  • Cleaning up temporary resources.
  • Restoring modified environment variables.
  • Closing external resources.
  • Removing temporary files.

RSpec Rails and transactional tests will handle much of our database cleanup automatically, so we shouldn’t manually delete every test record in after

let – lazy evaluation

Let’s understand its behaviour: let(:languages) { ["Ruby", "JavaScript", "Python"] } . And if you call it multiple times within the same example, RSpec reuses its cached value. This is called lazy evaluation and memoization.

Hands-on exercise

Let’s create another learning spec: touch spec/learning/rspec_setup_hooks_spec.rb

RSpec.describe "RSpec setup hooks" do
  let(:execution_log) { [] }

  let(:languages) do
    execution_log << :languages_created
    ["Ruby", "JavaScript", "Python"]
  end

  before(:each) do
    execution_log << :before_hook
  end

  # Write your examples here
  it "Test lazy evaluation" do
    puts "execution_log: #{execution_log}"
  end
  
  it "Access let variable and check lazy evaluation when referenced" do
    expect(languages).to include("Ruby")
    puts "execution_log: #{execution_log}"
  end
  
  it "Access let variables twice within this example and verify lazy loading" do
    expect(languages).to include("Python")
    expect(languages).not_to include("Rust")
    puts "execution_log: #{execution_log}"
  end
end

We’ll now cover three important RSpec concepts that you’ll use extensively when writing Rails model specs and request specs:

  1. let! – eager evaluation.
  2. subject – defining the primary object under test.
  3. before(:all) vs before(:each) – setup lifecycle and execution order.

RSpec execution lifecycle

1. let vs let!

We already understand let. let!(:user) { "Abhilash" } The ! changes the behaviour.

# let - Lazy

Start example
    |
    v
Before hook
    |
    v
Execute example
    |
    v
Access user?
   /    \
  Yes     No
  |       |
Evaluate  Never
# let! - Eager

Start example
    |
    v
Execute let! setup
    |
    v
Before hooks (according to declaration order)
    |
    v
Execute example

Technically, let! is implemented by defining a let helper and registering a before hook that invokes it.

When should we use let!?

Consider a Rails model spec. Suppose we want to test whether a user has three tasks. We need those three tasks to exist before the example executes. This is a good use case for let!. let!(:task) { create(:task) }

We’ll eventually use FactoryBot’s create method here.

My recommendation: Prefer let by default. Use let! when the setup must happen before the example, regardless of whether the helper is explicitly accessed.

2. subject – the primary object under test

This is another important RSpec concept. Suppose we’re testing a method that normalizes a task title. Instead of repeatedly creating or referencing the main result, we can define it using subject.

subject(:normalized_title) do
  title.strip.downcase
end

Now we can use: expect(normalized_title).to eq("learn rails")

Why use subject?

Imagine testing a Task model with many examples. The primary object being tested is usually a Task instance. We can define:

subject(:task) do
  Task.new(title: "Learn Rails")
end

Then use: expect(task).to be_valid

Notice the difference:

letsubject
Defines reusable test dataDefines the primary object under test
Can define multiple helpersUsually one primary subject per example group
Access using its nameAccess using its name or subject
Lazy and memoizedLazy and memoized

A named subject such as subject(:task) also creates a helper called task.

What is the implicit subject?

RSpec also provides a default subject. For example:

RSpec.describe Array do
  it "starts empty" do
    expect(subject).to be_empty
  end
end

When the described class is an Array, RSpec’s implicit subject is a new instance of that class. You can also explicitly use: subject { described_class.new }

described_class refers to the class being tested.

Best practice: Prefer named subjects when they improve readability, especially in model specs.

3. before(:each) vs before(:all)

This is particularly important when working with database records.

HookExecutionState
before(:each)Before every exampleIsolated per example
before(:all)Once before the example groupShared across examples

before without arguments is equivalent to before(:each).

Example: before each

before(:each) do
  puts "Before each example"
end

Suppose there are three examples. Output:

Before each example
Example 1

Before each example
Example 2

Before each example
Example 3

Example: before all

before(:all) do
  puts "Before all examples"
end

Output:

Before all examples

Example 1
Example 2
Example 3

Important: Be careful with before(:all) and ActiveRecord

This is something I want you to remember for Rails development. RSpec Rails normally manages database transactions around individual examples. before(:all) runs outside that normal per-example transaction lifecycle. Consequently, database records created in before(:all) can leak between examples or require manual cleanup.

It can also result in shared mutable objects, making tests order-dependent.

My recommendation: For our Rails model and request specs, prefer let, let! and before(:each).

Use before(:all) only when you have a specific reason and understand its lifecycle implications.

Understand hook execution order

Suppose we have:

RSpec.describe "Outer" do
  before do
    puts "Outer before"
  end

  describe "Inner" do
    before do
      puts "Inner before"
    end

    it "runs example" do
      puts "Example"
    end
  end
end

What do you think the output will be?

It is: Outer before → Inner before → Example

The general rule is:

  • Parent group hooks run before nested group hooks.
  • Hooks registered within the same group run in declaration order.
  • let! internally registers a before hook at the point where it is declared, so declaration order can matter.

Practical assignment

Let’s combine what we’ve learned.

Let’s create another learning spec: touch spec/learning/rspec_lifecycle_spec.rb Implement the following exercises.

Exercise 1 – let!

Create an execution log. Define one let and one let!. Both should append different symbols to the execution log when evaluated.

Write an example verifying that:

  • The let! value is evaluated before the example.
  • The let value is not evaluated until referenced.

Exercise 2 – subject

Define a named subject called normalized_title. Its implementation should remove leading/trailing whitespace and convert a string to lowercase.

Verify that: " LEARN RAILS " produces: "learn rails"

Exercise 3 – Memoization

Access your named subject twice. Use an execution counter or log to verify that its block is evaluated only once within the same example.

Exercise 4 – Hook ordering

Create nested outer and inner example groups with before hooks. Predict and then verify the execution order. Run:

bundle exec rspec spec/learning/rspec_lifecycle_spec.rb --format documentation


RSpec.describe "Test rspec lifecycle hooks" do
  let(:execution_log) { [] }
  let(:title) { "  LEARN RSPEC  " }

  subject(:normalized_title) do
    execution_log << :subject_executed
    puts "subject execution_log: #{execution_log}"
    title.downcase.strip
  end

  let(:animal) do
    execution_log << :animal
    "Lion"
  end

  let!(:bird) do
    execution_log << :bird
    "Eagle"
  end

  describe "let and let!" do
    it "test let! evaluation" do
      expect(execution_log.count(:animal)).to eq(0)
      expect(execution_log.count(:bird)).to eq(1)
      expect(execution_log.count(:subject_executed)).to eq(0)
    end
  end

  describe "test subject lazyness" do
    it "call subject and check the counter" do
      normalized_title
      subject
      expect(execution_log.count(:subject_executed)).to eq(1)
    end
  end

  before do
    p "Outer hook"
  end

  describe "Test hook ordering" do
    before do
      p "Inner hook"
    end
    it "test inner hook" do
      expect(execution_log.count(:subject_executed)).to eq(0)
      expect(execution_log.count(:animal)).to eq(0)
      expect(execution_log.count(:bird)).to eq(1)
    end
  end
end

This is a good demonstration of eager versus lazy evaluation.

Remember this distinction:

LocationSyntax
Declarationsubject(:normalized_title) { ... }
Access inside examplenormalized_title
Access using default namesubject

A few observations before moving on:

  1. subject(:normalized_title) is lazy. It executes only when accessed.
  2. Calling normalized_title and then subject accesses the same memoized subject. The block executes only once per example.
  3. let!(:bird) executes automatically before each example, including examples in nested groups.
  4. let(:animal) never executes in your current examples because you don’t access it.

Web Application Testing: Rails, RSpec, Puppeteer and Playwright

Testing is a critical part of building reliable web applications. However, choosing the right testing tools and deciding what to test at each layer can be confusing, especially when working with Ruby on Rails, React and separate API services.

In this guide, we’ll cover four types of tests, Rails examples, browser automation tools and a recommended testing architecture for modern web applications.

1. Understanding the Four Types of Tests

A good testing strategy uses different testing layers rather than testing everything through a browser.

1. Unit Tests

Purpose: Test a small, isolated piece of business logic.

Examples include price calculations, validations, discount rules, and service objects.

# app/services/discount_calculator.rb
class DiscountCalculator
  def self.apply(price:, percent:)
    price * (100 - percent) / 100.0
  end
end

RSpec example:

RSpec.describe DiscountCalculator do
  it "calculates a discounted price" do
    result = described_class.apply(
      price: 100,
      percent: 10
    )

    expect(result).to eq(90)
  end
end

Characteristics:

  • Fast and easy to debug.
  • Tests business rules independently.
  • Usually avoids databases, network calls, and browsers.

Unit tests provide a strong foundation for an application, but they cannot prove that all components work together.

2. Integration and Request Tests

Purpose: Verify that multiple components work together correctly.

In Rails, request specs are especially useful for testing API endpoints, HTTP status codes, response bodies, authorization, and database side effects.

# spec/requests/api/products_spec.rb
RSpec.describe "GET /api/products", type: :request do
  it "returns products as JSON" do
    product = create(:product, name: "Trail Shoes")

    get "/api/products"

    expect(response).to have_http_status(:ok)

    json = JSON.parse(response.body)

    expect(json.map { |item| item["id"] })
      .to include(product.id)
  end
end

This tests the HTTP request and response through Rails, without opening a browser.

Other important scenarios include:

  • Authentication and authorization.
  • Invalid parameters and validation errors.
  • Database interactions.
  • API error handling and response formats.

Characteristics: More realistic than isolated unit tests, generally faster and less brittle than browser tests.

RSpec supports model, request, job, mailer, system, and other spec types. Therefore, RSpec is not limited to unit testing. See the RSpec Rails documentation.

3. Frontend Component Tests

Purpose: Test individual UI components and their user-visible behavior.

For a React frontend, you can use Vitest with React Testing Library.

For example, a search component should display matching results or an appropriate empty state when users search.

import { render, screen } from "@testing-library/react";
import { describe, it, expect } from "vitest";
import SearchMessage from "./SearchMessage";

describe("SearchMessage", () => {
  it("shows an empty-state message", () => {
    render(<SearchMessage results={[]} />);

    expect(
      screen.getByText("No products found")
    ).toBeInTheDocument();
  });
});

This assumes SearchMessage renders the specified text when its results array is empty and that the testing dependencies are configured.

Component tests are useful for:

  • Form validation and error messages.
  • Loading and empty states.
  • Button interactions.
  • Rendering based on props and state.

They usually do not require a real browser or a running Rails API.

See React Testing Library.

4. End-to-End (E2E) Browser Tests

Purpose: Test a complete user journey through a real browser.

For example:

  1. User signs in.
  2. Searches for a product.
  3. Adds it to the cart.
  4. Completes checkout.
  5. Sees an order confirmation.

These tests can detect integration problems across the frontend, backend, browser, and database that isolated tests may miss.

However, they are generally slower and require more setup. Consequently, you should prioritize critical workflows instead of testing every button or input through a browser.

❓ 2. Is RSpec the Best Testing Framework for Enterprise Applications?

This assumption is partly correct.

RSpec is popular in Rails applications because it offers an expressive testing DSL, useful matchers, shared examples, mocking support, and a mature ecosystem. These features can make tests easier to write and maintain.

However, there are two important distinctions.

First, RSpec is not the same as unit testing.

You can use RSpec for all of these:

  • Unit tests.
  • Request and integration tests.
  • Background job tests.
  • Browser-based system tests.

A project may use RSpec extensively but have very few isolated unit tests. For example, if most specs exercise HTTP endpoints, its test suite may be heavily integration-oriented.

Second, RSpec is not automatically faster than other testing frameworks.

Rails includes Minitest by default. Both Minitest and RSpec can support maintainable, comprehensive test suites. Overall execution time depends heavily on database setup, test isolation, factories, external services, parallelization, and the proportion of browser tests.

The best choice is the framework that fits your team’s conventions, expertise, and application requirements.

3. Puppeteer vs. Rails System Tests

Puppeteer is a JavaScript library for controlling browsers programmatically. It can automate clicks, form submissions, page navigation, screenshots, and other browser activities.

It is not a Rails testing framework.

What is the equivalent in Rails?

There is no exact one-to-one replacement, but the closest built-in Rails equivalent is system testing using Capybara and a browser driver.

Rails system tests integrate browser automation with your Rails testing environment. You can interact with links, forms, buttons, JavaScript behavior, and page content.

Example:

# spec/system/product_search_spec.rb
RSpec.describe "Product search", type: :system do
  it "shows matching products" do
    create(:product, name: "Trail Shoes")

    visit "/products"

    fill_in "Search", with: "Trail"
    click_button "Search"

    expect(page).to have_text("Trail Shoes")
  end
end

This example assumes a server-rendered Rails page with a search field labeled “Search” and a corresponding button.

In an RSpec project, configure system specs with Capybara and an appropriate browser driver, such as Selenium. Other supported driver integrations are available.

See the Rails Testing Guide.

Comparison

ToolMain use
RSpecBackend and Rails application testing
CapybaraHigh-level API for interacting with web pages
SeleniumBrowser automation driver
PuppeteerJavaScript browser automation
PlaywrightBrowser automation and end-to-end testing

These tools are not all direct competitors. For example, RSpec and Playwright can be used in the same project because they test different layers.

❓ 4. What Is Playwright and When Should You Use It?

Playwright is a browser automation and testing framework. It supports Chromium, Firefox, and WebKit, and provides a test runner, assertions, browser contexts, and automatic waiting for many browser actions.

This makes it especially useful for modern JavaScript applications.

See the Playwright documentation.

React + Rails API: My Recommendation

Suppose you build an application with:

  • React + Vite for the frontend.
  • Ruby on Rails for the API.
  • PostgreSQL for persistence.

I would recommend the following:

Testing requirementRecommended tool
Rails business logicRSpec unit specs
Rails API endpointsRSpec request specs
React componentsVitest + React Testing Library
Complete user journeysPlaywright

Playwright is a strong default for E2E tests in this architecture because it can run independently of the Rails testing framework and interact with the deployed or locally running React application.

For example, a Playwright test might open the React application, enter a search term, verify the displayed products, add one to the cart, and complete a checkout flow against a test Rails API.

You can still use Rails system tests if you prefer a Ruby-based browser-testing workflow. However, Playwright often provides a more natural fit when the frontend is a separately developed React application.

My preference: Use RSpec for backend behavior and Playwright for critical cross-application browser journeys. Avoid duplicating every backend test in Playwright.

❓ 5. Are Browser Tests, System Tests and E2E Tests the Same?

This terminology causes considerable confusion because different tools and teams use these terms differently.

  • Browser test: A broad term for a test that drives an actual browser.
  • System test in Rails: A Rails testing category that exercises the application through a browser, typically using Capybara.
  • E2E test: A test that validates a complete workflow across the components involved in that workflow.

A Rails system test that signs in, purchases a product, and verifies the confirmation page is also an E2E test in the broader sense.

Likewise, a Playwright test can be an E2E test.

Not every browser test must be a full E2E test. For example, a browser test might verify that a dropdown opens correctly without exercising the backend.

Remember that system testing is a specific Rails testing facility, whereas E2E describes the scope and purpose of a test.

☑️ 6. Recommended Testing Architecture

For a typical production web application, I recommend the following strategy:

LayerToolPriority
UnitRSpecHigh
Integration / APIRSpec request specsHigh
Frontend componentsVitest + Testing LibraryHigh for substantial JS frontends
E2E browser workflowsPlaywright or Rails system testsCritical user journeys

A practical CI strategy is:

  1. Run unit, request, and component tests on every pull request.
  2. Run a small set of critical E2E tests on every pull request when execution time permits.
  3. Run broader browser coverage, including additional browser engines where required, on a scheduled or pre-release basis.
  4. Scan dependencies and run relevant security checks as part of CI.

The goal is not to maximize the number of tests. The goal is to catch defects quickly and reliably at the lowest reasonable level.

For example, test twenty discount calculation edge cases with unit tests rather than maintaining twenty browser tests for the same business rules. Then use a few E2E tests to prove that the essential shopping journey works.

🎯 The Conclusion

For a conventional Rails application, RSpec with request specs and a carefully selected set of system tests can be sufficient.

For a React + Rails API application, I recommend:

  • RSpec for business logic and backend integration.
  • Vitest + React Testing Library for frontend components.
  • Playwright for important E2E journeys.

Puppeteer is also capable of browser automation, but there is no need to introduce it merely because it is popular in JavaScript projects.

The best testing architecture is a balanced suite that verifies business rules, API behavior, frontend interactions, and critical end-to-end workflows without making every test expensive to maintain.