Create TaskManager app: Setup backend – Rails models, tables 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.

Create TaskManager app: Setup Ruby on Rails backend, react frontend, postgresql, Rspec

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.

Ractors and Ruby Box in Ruby 4: What Do They Mean for Rails?

Ruby 4.0 introduced two fascinating runtime capabilities:

  • Ractors, significantly improved for parallel execution
  • Ruby Box, an experimental mechanism for isolating definitions inside one Ruby process

For a Rails developer, the obvious question is:

Can I take my existing Rails application and simply add Ractors and Ruby Box to make it faster or more scalable?

The answer is not yet that simple.

Ractors can be extremely useful for carefully isolated CPU-heavy work, but a conventional Rails application is deeply interconnected through global state, constants, classes, ActiveSupport, ActiveRecord, gems, configuration and caches.

Ruby Box is a completely different concept. It is not primarily a parallelism mechanism. It provides in-process isolation of definitions and loaded code, with potential applications such as running multiple application versions in one Ruby process. Ruby 4.0 documents it as experimental.

Let’s look at both from a Rails perspective.


1. First: what problem does a Ractor solve?

A normal Ruby thread looks roughly like this:

Rails process
│
├── Thread 1
├── Thread 2
├── Thread 3
└── Thread 4
│
└── same Ractor / same GVL

Threads within a Ractor still share that Ractor’s GVL, so they don’t execute Ruby code in parallel with one another.

Ractors change the model:

Rails process
│
├── Ractor A ── GVL ── Thread(s)
│
├── Ractor B ── GVL ── Thread(s)
│
└── Ractor C ── GVL ── Thread(s)

Different Ractors can execute Ruby code in parallel on different CPU cores. Ruby 4.0 also reduced internal contention and introduced Ractor::Port for communication.

That makes Ractors especially interesting for CPU-bound work.


2. What should NOT be your first Ractor experiment?

Suppose you have:

class ReportsController < ApplicationController
  def show
    @report = Report.generate
  end
end

It is tempting to write:

def show
  r = Ractor.new do
    Report.generate
  end

  @report = r.value
end

This is exactly the kind of approach that exposes the biggest problem.

A Rails application has a huge amount of shared framework state.

For example:

Rails
│
├── ActiveSupport
├── ActiveRecord
├── Zeitwerk
├── configuration
├── caches
├── logging
├── autoloading
├── class/module definitions
└── gems

Ractors deliberately restrict access to non-shareable objects across Ractors.

The Ruby documentation says that most objects are unshareable and communication between Ractors is intended to happen through shareable objects or message passing.

That makes a normal Rails application a poor candidate for simply wrapping arbitrary Rails calls inside Ractor.new.

There has also been a real Rails issue demonstrating Ractor::IsolationError when attempting to instantiate or use Rails application state from a non-main Ractor.


3. The better idea: use Ractors around isolated computation

Instead of:

Ractor
↓
Entire Rails application

think:

Rails
│
├── request
│
├── database work
│
└── isolated CPU calculation
↓
Ractor

For example, imagine a report containing millions of values.

class ReportCalculator
  def self.calculate(numbers)
    numbers.sum { |n| expensive_calculation(n) }
  end

  def self.expensive_calculation(n)
    # CPU-heavy calculation
    n ** 3
  end
end

You could partition the data:

chunks = numbers.each_slice(10_000).to_a

ractors = chunks.map do |chunk|
  Ractor.new(chunk) do |values|
    values.sum { |n| n ** 3 }
  end
end

result = ractors.sum(&:value)

The important architectural boundary is:

Rails
│
│ plain data
▼
Ractor 1 ── CPU work ──┐
Ractor 2 ── CPU work ──┼──→ results
Ractor 3 ── CPU work ──┘
│
▼
Rails

This is much more promising.

The Ractors don’t need to manipulate:

ActiveRecord::Relation
Rails.application
ActiveSupport::Cache
Controller
request
response

They receive isolated data and return isolated results.


4. A practical Rails use case: analytics

Imagine:

orders = Order
.where(created_at: 30.days.ago..)
.pluck(:amount)

The database query happens normally.

Then:

chunks = orders.each_slice(50_000).to_a

ractors = chunks.map do |chunk|
  Ractor.new(chunk) do
    {
      total: chunk.sum,
      average: chunk.sum.to_f / chunk.length
    }
  end
end

results = ractors.map(&:value)

total = results.sum { |r| r[:total] }

The database remains Rails’ responsibility.

The CPU-heavy aggregation becomes parallel work.

That is the mental model I’d recommend:

Use Rails for orchestration; use Ractors for isolated computation.

The above code can be Optimized. Check: https://railsdrop.com/optimization-fix-the-memory-heavy-ruby-operation/


5. Another good candidate: document/image processing

Suppose your application performs CPU-heavy transformations:

PDF
↓
parse
↓
transform
↓
calculate
↓
generate result

Instead of letting one Ruby execution stream process everything:

Rails
│
└── CPU-heavy processing

you can potentially build:

                    Rails
                      │
               Job / Service
                      │
          ┌───────────┼───────────┐
          ▼           ▼           ▼
       Ractor      Ractor      Ractor
         │           │           │
       file A      file B      file C
          └──────────┬──────────┘
                     ▼
                   result

The same principle applies to:

  • compression
  • large JSON transformations
  • encryption-related computation
  • parsing
  • ranking/scoring
  • simulations
  • large in-memory calculations

The exact benefit depends heavily on whether the work is CPU-bound and whether the cost of copying/moving data outweighs the parallelism benefit.

Ruby’s Ractor documentation explicitly notes that unshareable objects may be copied or moved between Ractors, so data-transfer overhead must be considered.


6. Ractor is not a replacement for ActiveJob

It is important not to confuse these abstractions.

For example:

SomeJob.perform_later(order.id)

and:

Ractor.new(...)

solve different problems.

ActiveJob/Sidekiq/GoodJob/etc. solve background job execution and process-level application architecture.

Ractors solve parallel execution inside one Ruby process.

You could potentially combine them:

Rails
│
▼
Background Job
│
▼
Ruby Process
│
├── Ractor 1
├── Ractor 2
├── Ractor 3
└── Ractor 4

But this is an advanced optimization, not the default architecture.


7. So where does Ruby Box fit?

Ruby Box is much less about CPU parallelism.

Its purpose is definition isolation.

Suppose you have:

class User
def role
"admin"
end
end

Now imagine loading another piece of code that reopens User:

class User
def role
"guest"
end
end

Normally, that’s a global change to the Ruby process.

Ruby Box lets those definitions exist in separate boxes.

Conceptually:

Ruby process
│
├── Main box
│ └── User#role → "admin"
│
└── Box B
└── User#role → "guest"

Ruby’s documentation describes this as isolation of class/module definitions, monkey patches, constants, global/class variables and loaded Ruby/native libraries.

This is a very different problem from Ractors.


8. A simple Ruby Box example

Ruby Box must be enabled at process startup:

RUBY_BOX=1 ruby app.rb

Setting the variable after Ruby has already started does not enable it.

Then:

box = Ruby::Box.new
box.require("./legacy_user.rb")

Suppose legacy_user.rb contains:

class User
def role
"legacy"
end
end

The definition is loaded into the box.

Conceptually:

Main box
│
└── User
Legacy box
│
└── User
└── role → "legacy"

The definition in the box is isolated from the corresponding definition in other boxes. Ruby’s documentation demonstrates this with constants, classes and methods.


9. This has a fascinating Rails use case: blue-green application versions

This is one of the use cases Ruby itself proposes.

Imagine:

One Ruby process
┌─────────────────────────────┐
│ Ruby Process │
│ │
│ Box A │
│ Rails App v1 │
│ │
│ Box B │
│ Rails App v2 │
└─────────────────────────────┘

Ruby 4.0 explicitly lists running web-app boxes in parallel as a potential blue-green deployment use case.

Theoretically, this gives you the ability to have:

/app-v1
/app-v2

loaded in separate definition environments inside the same Ruby process.

Then requests could be directed to:

traffic
│
├──→ Box A
│
└──→ Box B

This could eventually enable interesting deployment and migration strategies.

But there is a huge caveat.


10. Ruby Box is experimental

This is not currently something I’d take into a normal Rails production deployment simply because Ruby 4 has it.

The official documentation lists known issues, including:

  • native extension installation problems
  • require 'active_support/core_ext' potentially failing
  • limitations around methods defined in a box being called by built-in Ruby methods

and other TODO items.

That is especially important for Rails.

Rails isn’t a small collection of isolated classes.

It has a large dependency graph:

Rails
│
├── ActiveSupport
├── ActiveRecord
├── ActionPack
├── Zeitwerk
├── Rack
├── Bundler
├── native extensions
└── hundreds of possible gems

Isolating an entire Rails application therefore involves considerably more than:

box = Ruby::Box.new
box.require("app")

11. Ruby Box could be more interesting for development and testing first

One of Ruby’s proposed Ruby Box use cases is isolating tests that perform monkey patches.

Consider:

class String
def special
"patched"
end
end

Normally this contaminates the process.

A box can potentially isolate that modification:

Test process
│
├── Main box
│ └── normal String
│
├── Test Box A
│ └── patched String
│
└── Test Box B
└── different String definition

Ruby itself lists isolated test execution as an expected use case.

For a large test suite, this is an interesting direction.


12. How I would use Ractors in a new Rails application

I wouldn’t architect the entire application around Ractors.

Instead:

                    Rails
                      │
      ┌───────────────┼────────────────┐
      │               │                │
   HTTP/API        ActiveRecord     Background Jobs
      │
      │
      └────── CPU-heavy service ───────┐
                                       │
                          ┌────────────┼────────────┐
                          ▼            ▼            ▼
                       Ractor       Ractor       Ractor

Keep Rails state out of the Ractors wherever possible.

Design explicit boundaries:

input = {
values: values,
options: options
}

rather than:

ractor = Ractor.new do
Order.where(...)
end

The first is an isolated computation.

The second makes the Ractor responsible for Rails state.

That’s where the complexity explodes.


13. How I would introduce Ractors into an existing Rails app

Start with one measurable CPU bottleneck.

For example:

Before
request
↓
large calculation
↓
1 CPU core
↓
response

Then extract:

class PricingCalculator
def self.calculate(input)
# pure Ruby calculation
end
end

Make it as pure as possible:

result = PricingCalculator.calculate(
prices: prices,
rules: rules
)

Then experiment with:

Ractor.new(input) do |data|
PricingCalculator.calculate(data)
end

Benchmark both:

single-threaded
vs
multiple Ractors

Don’t assume parallelism automatically means faster execution.

You need to measure:

  • CPU time
  • wall-clock time
  • memory usage
  • object copying
  • Ractor startup
  • throughput
  • latency

14. Rails architecture: where each feature fits

A useful mental model is:

                    Rails
                      │
     ┌────────────────┼─────────────────┐
     │                │                 │
     ▼                ▼                 ▼
   Web              Data             Jobs
     │                │                 │
     └────────────────┴────────┐        │
                               ▼        ▼
                       Application services
                               │
                       CPU-heavy workload
                               │
                         ┌─────┴─────┐
                         ▼           ▼
                      Ractor      Ractor

Ruby Box sits at a different architectural layer:

Ruby Process
│
├── Main / Application Box
│
├── Application Box A
│
└── Application Box B

So:

Ractor = parallel execution

while:

Ruby Box = definition/environment isolation

They solve different problems.


15. The big Rails limitation today

This is the part worth remembering.

A conventional Rails application is built around a substantial amount of shared application state.

That doesn’t fit naturally with Ractor’s isolation model.

There has been an explicit Rails issue requesting Ractor support and that issue was closed as “not planned.” The discussion showed Ractor::IsolationError arising from Rails class-level state.

https://github.com/rails/rails/issues/51543

That doesn’t mean Rails can never become Ractor-friendly.

It means:

Don’t interpret Ruby 4’s Ractor improvements as “Rails is now automatically Ractor-safe.”

Those are two different layers.

Ruby’s runtime may support the concurrency primitive while the framework ecosystem still has architectural work to do.

Read for more info: https://discuss.rubyonrails.org/t/ractor-safe-rails/91277


16. The practical strategy for a Rails developer

For an existing Rails application:

1. Find CPU-bound code
2. Extract it from Rails state
3. Make inputs/outputs explicit
4. Benchmark it
5. Try Ractors
6. Measure copying + memory
7. Keep the rest of Rails unchanged

For a new application:

Rails
↓
thin controllers
↓
application services
↓
pure computation
↓
Ractor boundary

That architecture gives you a much better chance of benefiting from parallel Ruby.

For Ruby Box:

Development/testing first
↓
isolated definitions
↓
experimentation
↓
specialized deployment scenarios

rather than immediately attempting:

"Let's run the whole Rails app in 10 Ruby Boxes."

Final takeaway

Ruby 4 did something more interesting than simply making threads faster.

It is giving Ruby developers more explicit runtime tools:

Ractor
↓
parallel Ruby computation
Ruby Box
↓
isolated Ruby definitions
YJIT / ZJIT
↓
faster execution
GC/runtime improvements
↓
less overhead

For Rails, however, the winning strategy isn’t:

“Convert Rails to Ractors.”

It is:

“Keep Rails responsible for application orchestration and isolate carefully chosen CPU-heavy computations behind Ractor boundaries.”

And Ruby Box is even more experimental.

Its long-term Rails potential may actually be more architectural than performance-oriented: isolating application versions, tests, plugins, or dependency environments inside one Ruby process.

The exciting thing is that Ruby 4 gives us primitives that make these designs possible.

The engineering challenge is deciding where the boundary belongs.

That is ultimately the same lesson we’ve been following through this series:

Ruby gives us abstractions. Understanding the runtime lets us decide when to cross them.

A useful next post in this series would be “Ractor vs Thread vs Process in Rails: when should a senior Rails developer choose each?” – with real benchmarks, memory/CPU trade-offs and a Sidekiq/Puma/Ractor architecture comparison.

Rails Encrypted Credentials: The Git Diff Feature You May Have Been Using Without Knowing

If you have been developing Rails applications for years, there’s a good chance you’ve used:

bin/rails credentials:edit

hundreds of times.

You probably know that Rails stores encrypted credentials in:

config/credentials.yml.enc

and keeps the encryption key separately in:

config/master.key

But did you know that Rails can make:

git diff

show the decrypted, human-readable changes to credentials.yml.enc?

I recently discovered this while working on a Rails 8.1.3.1 application and it was one of those:

“I’ve been using Rails every day for years, and I didn’t know Rails could do this!”

moments.

Let’s see how it works.


First: What is credentials.yml.enc?

Rails encrypted credentials allow us to keep secrets such as:

openai:
  api_key: ...

or:

aws:
  access_key_id: ...
  secret_access_key: ...

inside:

config/credentials.yml.enc

The file is encrypted.

The encryption key is stored separately in:

config/master.key

Rails documentation explicitly states that the encrypted credentials file can be stored in version control as long as the master key remains secure. (Ruby on Rails Guides)

So our repository can contain:

config/
├── credentials.yml.enc ← encrypted, safe to commit
└── master.key ← secret, NEVER commit

Editing Rails Credentials

Normally we edit credentials with:

bin/rails credentials:edit

Rails decrypts the credentials, opens them in your configured editor, and encrypts them again when you save.

Conceptually:

credentials.yml.enc
        │
        │ decrypt
        ▼
   Plain YAML
        │
        │ edit
        ▼
   Plain YAML
        │
        │ encrypt
        ▼
credentials.yml.enc

The plaintext credentials aren’t saved as a normal file.

But What Happens With git diff?

Here’s the interesting part.

If Git simply compared the encrypted files, we’d get something useless:

- 3d9Jx8...random-encrypted-data...
+ 7kP2mL...different-encrypted-data...

We wouldn’t know:

  • Which credential changed?
  • Was a key added?
  • Was a key removed?
  • Did the API key change?
  • Did somebody accidentally modify something?

This is where Rails’ credentials diff integration becomes useful.

Rails + Git textconv

Rails can configure Git to use a special diff driver:

[diff "rails_credentials"]
textconv = bin/rails credentials:diff

In my Rails 8.1 application, I found exactly this in:

.git/config

Git therefore doesn’t simply compare the encrypted contents.

Instead:

git diff
    │
    ▼
Git sees credentials.yml.enc
    │
    ▼
rails_credentials diff driver
    │
    ▼
bin/rails credentials:diff
    │
    ▼
Rails decrypts the credentials
    │
    ▼
Git displays a readable diff

Git itself doesn’t understand Rails encryption.

Rails is providing the text conversion command. Git simply knows how to invoke it.

See It Yourself

Suppose our credentials originally contain:

openai:
api_key: OLD_KEY

We change it to:

openai:
api_key: NEW_KEY

Now:

git diff

can show a useful diff such as:

+
+openai:
+ api_key: 'sdsdssdsdsdwewewddvcfgfgth'

That’s much more useful than comparing encrypted bytes.

The Experiment That Makes This Obvious

This is what made the behavior click for me.

Run:

git diff -- config/credentials.yml.enc

You get the human-readable credentials diff.

Now bypass Git’s text conversion:

git diff --no-textconv -- config/credentials.yml.enc

Now you see the encrypted content.

Something like:

3d9Jx8...encrypted-data...

That’s the proof.

The file itself is still encrypted.

It’s only the diff representation that’s being transformed.

So What Exactly Does Git Know?

Git doesn’t know anything about:

Rails
credentials
master.key
AES
encryption
decryption

Git knows:

diff driver
textconv

Rails configures:

rails_credentials

and tells Git:

When displaying a diff for this file,
run:
bin/rails credentials:diff

That’s a very nice example of two independent tools cooperating:

             Rails
               │
               │ provides
               ▼
       credentials:diff
               │
               ▼
             Git
               │
               │ uses
               ▼
           textconv

How Does Rails Configure It?

Rails provides:

bin/rails credentials:diff --enroll

This enrolls the project in credentials diffing.

The Git attributes include:

config/credentials/*.yml.enc diff=rails_credentials
config/credentials.yml.enc diff=rails_credentials

Rails then ensures the Git diff driver is configured to use:

bin/rails credentials:diff

Rails’ application generator includes this credentials diff enrollment as part of application setup and Rails 7.0 already contained the credentials diffing implementation. (Gem)

So this isn’t actually an 8.1-only feature.

That’s an important distinction.

Is This New in Rails 8.1?

No – and this is an important correction.

The encrypted credentials diff functionality existed before Rails 8.1.

For example, Rails 7.0 already had the credentials:diff implementation, and Rails 7.2’s application generator also enrolled projects in credentials diffing. (Gem)

Rails has supported decrypted Git diffs for encrypted credentials for several versions and Rails 8.x continues to build on the credentials tooling.

Rails 8.1 does introduce other useful credentials functionality. For example, Rails 8.1 added command-line credential fetching, which can be useful for deployment tooling such as Kamal. (Ruby on Rails Guides)

Does This Make My Secrets Unsafe?

No – provided you protect the master key.

The important distinction is:

Git repository
│
├── credentials.yml.enc
│       ↓
│   encrypted
│
└── master.key
        ↓
     SECRET

The encrypted file can be committed.

The master key should not be committed. Rails’ security guide explicitly recommends keeping the master key safe and out of version control. (Ruby on Rails Guides)

One Thing to Remember

The decrypted content can appear in your local terminal output.

For example:

git diff

could display:

+
+openai:
+  api_key: 'sdsdssdsdsdwewewddvcfgfgth'

So don’t casually share terminal screenshots containing credential diffs.

Also be careful when copying terminal output into:

  • Slack
  • GitHub issues
  • Pull requests
  • screenshots
  • blog posts
  • AI assistants

NOTE: The encryption protects the file stored in Git, but a decrypted diff is plaintext.

Rails Developer Takeaway

There are three different things here:

1. Encrypted file

config/credentials.yml.enc

This is what is actually stored in Git.

2. Encryption key

config/master.key

This decrypts the credentials and must remain secret.

3. Git diff representation

bin/rails credentials:diff

This is what allows us to see meaningful changes locally.

So:

                 GitHub
                   │
                   │ encrypted
                   ▼
       credentials.yml.enc
                   ▲
                   │
             master.key
             stays secret


Local git diff:

credentials.yml.enc
        │
        ▼
credentials:diff
        │
        ▼
decrypted representation
        │
        ▼
human-readable diff

Try This Yourself

If you’re working on a Rails application, check:

git config --show-origin --get-regexp 'diff|textconv|filter'

You may find:

file:.git/config diff.rails_credentials.textconv bin/rails credentials:diff

Then:

git diff --no-textconv -- config/credentials.yml.enc

Compare that with:

git diff -- config/credentials.yml.enc

The difference is a great way to understand what’s really happening.

Quick Reference

# Edit credentials
bin/rails credentials:edit

# Enroll project in credential diffing
bin/rails credentials:diff --enroll

# Normal readable diff
git diff

# Show the actual encrypted file diff
git diff --no-textconv -- config/credentials.yml.enc

# Inspect Git's configuration
git config --show-origin --get-regexp 'diff|textconv|filter'

# Check Git attributes
git check-attr diff -- config/credentials.yml.enc

Security rule:

 Y config/credentials.yml.enc → commit it
 X config/master.key          → NEVER commit it


Rails’ official security guide confirms that encrypted credentials can be stored in version control while the master key must remain protected. (Ruby on Rails Guides)

📚 References

Happy Coding!

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.


Ruby Beyond CRuby: Why JRuby and TruffleRuby Exist? What Ruby 4.0 Really Changed

In my previous posts, I looked at how Ruby code eventually reaches the VM, native runtime and CPU.

That naturally leads to another question:

Why is there more than one Ruby?

Most Ruby developers use CRuby/MRI and may never think about it. But Ruby is a language specification, not a single runtime implementation.

Today we have several implementations, with two particularly interesting alternatives:

JRuby – Ruby implemented on the JVM.

TruffleRuby – Ruby implemented using the GraalVM/Truffle ecosystem.

And then there is the increasingly interesting question:

Did Ruby 4 finally remove the GIL and solve Ruby’s performance/scalability problems?

Not exactly.

Let’s look at why these implementations exist and where Ruby 4.0 stands today.


Ruby is a language, not necessarily an implementation

When I write:

class User
  def greet
    "Hello"
  end
end

I’m writing Ruby language semantics.

But somebody has to implement those semantics.

There is no requirement that the implementation must be written in C.

So we can have:

                    Ruby Language
                         │
          ┌──────────────┼──────────────┐
          ▼              ▼              ▼
       CRuby           JRuby       TruffleRuby
          │              │              │
          ▼              ▼              ▼
       C / VM           JVM       GraalVM / Truffle

All three attempt to behave like Ruby while using very different execution technologies.


Why was JRuby created?

JRuby’s fundamental idea was:

What if Ruby could run on the JVM and take advantage of everything the JVM already provides?

The JVM already has:

  • mature garbage collection
  • JIT compilation
  • highly optimized threading
  • profiling
  • excellent runtime tooling
  • enormous Java libraries
  • mature production infrastructure

Instead of building all of that from scratch, JRuby puts a Ruby implementation on top of the JVM.

Ruby code
    │
    ▼
JRuby
    │
    ▼
JVM
    │
    ├── JIT
    ├── GC
    ├── Threads
    └── Java libraries
    │
    ▼
CPU

JRuby explicitly aims to provide Ruby without a global interpreter lock, true parallelism and integration with Java. (GitHub)

That makes JRuby particularly interesting for applications where Ruby needs to coexist with Java infrastructure.


JRuby’s biggest advantage: true parallel Ruby threads

In CRuby, ordinary Ruby threads are native threads, but Ruby execution within a single Ractor is constrained by its GVL.

JRuby takes a different approach.

Multiple Ruby threads can execute Ruby code concurrently because there is no equivalent global interpreter lock preventing Ruby threads from running in parallel.

Conceptually:

CRuby

Thread 1 ──┐
Thread 2 ──┼──→ GVL ──→ Ruby execution
Thread 3 ──┘

Whereas:

JRuby

Thread 1 ─────────────→ CPU Core 1
Thread 2 ─────────────→ CPU Core 2
Thread 3 ─────────────→ CPU Core 3

That can be extremely valuable for CPU-heavy or highly concurrent workloads.

JRuby 10 also moved to Java 21 and made invokedynamic optimization the default, taking advantage of more modern JVM capabilities. (blog.jruby.org)


Why TruffleRuby?

TruffleRuby comes from a completely different idea.

Instead of saying:

“Let’s implement Ruby using the JVM.”

the Truffle approach essentially says:

“Let’s implement Ruby on a framework designed to build highly optimizing language runtimes.”

TruffleRuby uses the Truffle framework and GraalVM.

Ruby source
     │
     ▼
TruffleRuby
     │
     ▼
Truffle AST / runtime
     │
     ▼
Graal compiler
     │
     ▼
Optimized machine code
     │
     ▼
CPU

The interesting part is that Truffle/Graal can observe running code and aggressively specialize and optimize it.

TruffleRuby’s project explicitly targets high performance for Ruby workloads, parallel execution without a global interpreter lock, native extensions and interoperability with Java and other languages in the GraalVM ecosystem. (GitHub)

GraalVM Doc: https://www.graalvm.org/latest/introduction/


TruffleRuby and JRuby solve a similar problem differently

This distinction is important.

CRubyJRubyTruffleRuby
Main technologyC + Ruby VMJVMTruffle + GraalVM
GVL for normal Ruby threadsYesNoNo
Parallel Ruby threadsLimited by GVLYesYes
JVM ecosystemNoExcellentExcellent
JITYJIT/ZJITJVM JITGraal
Native extensionsExcellentDifferent approachMany C extensions supported
StartupExcellentGenerally slowerDepends on configuration
Warm-upLowHigherHigher
Peak performanceVery goodVery goodExcellent for suitable workloads

The important lesson is:

There isn’t one universally “best Ruby”.

The optimal runtime depends on the workload.


Now the big question: Does Ruby 4 remove the GIL?

No.

And there is an important terminology correction.

CRuby generally calls it the GVL – Global VM Lock.

Ruby 4.0 did not remove it from normal Ruby threads.

Ruby’s documentation states that threads within the same Ractor share a ractor-wide GVL and therefore cannot execute Ruby code in parallel with each other. Threads belonging to different Ractors can execute in parallel.

Ractors are designed to provide parallel execution of Ruby code without thread-safety concerns. (Ruby Documentation)

So:

                    CRuby 4.0
                       │
          ┌────────────┴────────────┐
          ▼                         ▼
      Ractor A                  Ractor B
          │                         │
     Thread 1                   Thread 1
     Thread 2                   Thread 2
          │                         │
        one GVL                  one GVL
          │                         │
          └──────────┬──────────────┘
                     │
               parallel execution

This is a major distinction.

Ruby 4 did not say:

“GVL is gone.”

It moved Ruby’s concurrency model further toward Ractor-based parallelism.


Ruby 4.0 significantly improved Ractors

Ruby 4.0 invested heavily in reducing the contention that previously limited Ractor scalability.

The release notes specifically mention improvements such as:

  • lock-free structures for frozen strings and the symbol table
  • fewer locks in method-cache lookups
  • faster instance-variable access
  • reduced allocation contention
  • reduced CPU cache contention
  • fewer locks around object_id
  • fixes for deadlocks and GC races involving Ractors (Ruby)

This is a much deeper improvement than simply deleting one lock.

The architecture is moving toward:

Before

Ractor ──┐
Ractor ──┼── shared internal state ── contention
Ractor ──┘


Ruby 4 direction

Ractor A ── mostly independent state
Ractor B ── mostly independent state
Ractor C ── mostly independent state

             ↓

       less lock contention
       less cache contention
       better parallelism

Ruby 4 also introduced Ractor::Port as a new synchronization mechanism and added shareable Proc/lambda APIs.


Ruby 4’s bigger performance story: YJIT and ZJIT

Ruby 4.0 introduced ZJIT, the next-generation JIT compiler after YJIT.

The interesting part is that Ruby now has two very different JIT stories:

                 Ruby 4
                   │
          ┌────────┴────────┐
          ▼                 ▼
        YJIT               ZJIT
      mature              new
      production          experimental
          │                 │
          ▼                 ▼
    native machine code   native code

Ruby’s own release announcement is very clear:

ZJIT is faster than the interpreter, but not yet as fast as YJIT.

Ruby 4.0 therefore recommends experimentation rather than production deployment for ZJIT.

ZJIT is intended to raise Ruby’s performance ceiling through larger compilation units and SSA-based intermediate representation, while also making the compiler architecture more approachable for outside contributors.

So Ruby 4 did not replace YJIT with a magically faster JIT overnight.

It started building the next generation.


Ruby 4 also improved the GC and object system

Some of the most interesting Ruby 4 changes aren’t visible from Ruby syntax at all.

Ruby 4.0 includes improvements such as:

• Independent growth of GC heaps for different size pools
• Faster sweeping of pages containing large objects
• Faster Class#new
• Improved instance-variable storage
• Less GC overhead from write barriers
• Better handling of embedded large Bignums
• Faster object_id/hash operations

These changes target allocation, memory consumption, GC work, object access and general runtime overhead. (Ruby)

For a Rails application, these details matter because a significant amount of application work eventually becomes:

allocate
↓
object lives
↓
object becomes unreachable
↓
GC
↓
CPU + memory bandwidth

Improving that pipeline can produce real application-level benefits without changing your Rails code.


Ruby 4’s interesting new feature: Ruby Box

Ruby 4.0 also introduced an experimental feature called Ruby Box.

It allows definitions and changes to be isolated from other boxes.

That includes things like:

  • monkey patches
  • class/module definitions
  • class/global variables
  • loaded libraries

One proposed use case is running multiple isolated application versions in the same Ruby process – for example, blue/green deployment scenarios.

Conceptually:

Ruby Process
│
├── Box A → Application version A
│
├── Box B → Application version B
│
└── Box C → Experiment

This is quite different from the normal Ruby process model and could become more interesting over time.


So did Ruby 4 “fix Ruby performance”?

No single release can be described that way.

Ruby’s performance problem has never been just one problem.

There are several:

Ruby performance
│
├── Interpreter overhead
├── Method dispatch
├── Object allocation
├── Garbage collection
├── Memory/cache behaviour
├── JIT compilation
├── Lock contention
└── Parallel execution

Ruby 4 improves several of these.

But each improvement has trade-offs.


Ruby 4: the best features

For an experienced Ruby/Rails developer, I would highlight these:

1. Better parallelism

Ractors are substantially more mature and have significantly less internal contention. (Ruby)

2. Better JIT direction

YJIT remains the mature choice, while ZJIT establishes a new JIT architecture with a higher long-term performance goal.

3. Runtime and GC improvements

Allocation, sweeping, object access and GC overhead have all received attention.

4. Ruby Box

A fascinating new isolation primitive that may eventually influence how long-running Ruby processes host multiple isolated applications.

5. Ecosystem maturity

Ruby 4 continues to preserve the programming model that makes Rails productive while the runtime underneath becomes increasingly sophisticated.


But Ruby 4 still has limitations

The biggest one is straightforward:

Normal Ruby threads still don’t provide unrestricted CPU parallelism inside one Ractor.

The GVL remains part of CRuby’s threading model. (Ruby Documentation)

There are also practical considerations around Ractors: code must respect Ractor isolation and shareability rules and not every gem or application architecture will naturally benefit from them.

And ZJIT is not yet a drop-in reason to turn off YJIT and deploy it everywhere; Ruby 4.0’s own release notes explicitly say it is not yet as fast as YJIT and recommend holding off on production use.


What about Ruby 4 vs JRuby and TruffleRuby?

This is where Ruby becomes particularly interesting.

                       Ruby
                        │
       ┌────────────────┼────────────────┐
       │                │                │
       ▼                ▼                ▼
     CRuby             JRuby        TruffleRuby
       │                │                │
       ▼                ▼                ▼
     C/VM              JVM        Graal/Truffle
       │                │                │
       ▼                ▼                ▼
     YJIT             JVM JIT        Graal JIT
       │                │                │
       ▼                ▼                ▼
    Ractors         real threads    real threads

CRuby’s advantage is its enormous compatibility, mature ecosystem, excellent startup characteristics and continued optimization of the standard implementation.

JRuby’s strength is the JVM: parallel Ruby threads and access to the Java ecosystem.

TruffleRuby’s strength is aggressive specialization and Graal-based optimization, with parallel Ruby execution and polyglot capabilities. Its maintainers report very high performance on appropriate benchmark workloads, though warm-up and compatibility remain practical considerations.


My conclusion as a Ruby developer

I think the most important change is not:

“Ruby 4 removed the GIL.”

It didn’t.

The more accurate statement is:

Ruby is steadily evolving from a primarily interpreter-centric runtime toward a highly optimized, JIT-driven, increasingly parallel execution platform.

The interesting evolution looks like this:

Old Ruby
   │
   ▼
Interpreter
   │
   ▼
GVL
   │
   ▼
Threads mostly for concurrency


Modern Ruby
   │
   ├── YJIT
   ├── ZJIT
   ├── better GC
   ├── better object representation
   ├── reduced lock contention
   └── Ractors
           │
           ▼
      parallel Ruby

And this is exactly why learning C and runtime internals is becoming more valuable.

When you understand memory, object allocation, GC, locks, CPU caches, JITs, threads and process boundaries, Ruby 4’s changes stop looking like a collection of release notes.

You start seeing the bigger picture:

The Ruby language hasn’t changed its philosophy of developer productivity. The runtime underneath it is becoming increasingly sophisticated at extracting performance from that high-level language.

As of August 2026, the current stable Ruby 4 branch is Ruby 4.0, with Ruby 4.0.6 released on July 14, 2026. (Ruby)

And that makes this a perfect point in the series to go one level deeper:

What actually happens inside a Ractor, how its GVL differs from the old “global” model and how Ruby can execute Ruby code in parallel without simply removing thread safety?

Happy Rubying!

What Really Happens When Ruby Code Executes?

As Ruby developers, we normally think execution is simple:

ruby app.rb

Ruby runs the file.

But what exactly is ruby?

Does the CPU execute Ruby code directly?

What is the Ruby interpreter?

Where does bytecode come into the picture?

What exactly is the runtime?

And where do C, machine code and the operating system enter the story?

For a developer who wants to understand Ruby beyond the language syntax, these are important questions.

This article follows a small Ruby program from source code all the way down to CPU execution.

Note: The discussion here focuses on CRuby/MRI- the standard Ruby implementation. Details differ in JRuby, TruffleRuby and other implementations. Ruby’s RubyVM APIs are explicitly MRI-specific. (docs.ruby-lang.org)


1. Start with a simple Ruby class

Consider this file:

# person.rb

class Person
  def initialize(name)
    @name = name
  end

  def greet
    "Hello, #{@name}"
  end
end

person = Person.new("Ruby")
puts person.greet

We execute it:

ruby person.rb

So what happens after we press Enter?


2. ruby is an executable program

When we type:

ruby person.rb

the shell does not understand Ruby syntax.

It finds the ruby executable in your PATH.

For example:

which ruby

might return:

/usr/bin/ruby

or perhaps a version-manager path such as:

/Users/me/.rbenv/shims/ruby

That executable is a compiled native program.

This is a crucial distinction:

Ruby source code is not itself executed by the operating system. The operating system starts the Ruby executable, and that program executes your Ruby program.

The flow initially looks like this:

Terminal
   │
   │ ruby person.rb
   ▼
Shell
   │
   │ locate executable
   ▼
Ruby executable
   │
   ▼
Operating System creates process

The ruby process is now running.


3. The Ruby interpreter is inside that process

People often say:

“Ruby interprets my code.”

This is useful shorthand, but the reality is more interesting.

The Ruby executable contains the runtime machinery necessary to:

  • read Ruby source
  • parse it
  • compile it
  • create internal structures
  • execute VM instructions
  • manage Ruby objects
  • run garbage collection
  • perform method calls
  • interact with the operating system

So we can think of:

ruby executable
       │
       ├── parser
       ├── compiler
       ├── VM
       ├── garbage collector
       ├── object system
       └── runtime libraries

This collection of mechanisms is what we generally mean by the Ruby runtime.


4. Source code is first parsed

Our source:

person = Person.new("Ruby")

is not immediately converted into CPU instructions.

Ruby first needs to understand its structure.

The parser turns the source into an internal representation of the program.

Conceptually:

Ruby source
    │
    ▼
Tokenizer / Parser
    │
    ▼
Internal syntax representation

For example, Ruby has to understand:

Person.new("Ruby")

as roughly:

receiver: Person
method:    new
argument:  "Ruby"

The exact internal representation is an implementation detail, but the important point is:

Ruby must understand the program before it can execute it.


5. Ruby then compiles the code into VM instructions

This is the part many Ruby developers don’t realize.

CRuby does not normally execute the original Ruby source line-by-line.

The code is compiled into instructions for Ruby’s virtual machine.

These are commonly referred to as YARV instructions or Ruby bytecode.

Ruby exposes this machinery through:

RubyVM::InstructionSequence

For example:

puts RubyVM::InstructionSequence.compile(
  'puts "Hello"'
).disasm
== disasm: #<ISeq:<compiled>@<compiled>:1 (1,0)-(1,12)>
0000 putself                                                          (   1)[Li]
0001 putchilledstring                       "Hello"
0003 opt_send_without_block                 <calldata!mid:puts, argc:1, FCALL|ARGS_SIMPLE>
0005 leave
=> nil

You will see VM instructions rather than Ruby source.

The exact output changes between Ruby versions because the instruction set and compiler details are implementation-specific. Ruby documents InstructionSequence specifically as a way to inspect the VM’s compiled instructions.

So our pipeline becomes:

person.rb
   │
   ▼
Parser
   │
   ▼
Ruby internal representation
   │
   ▼
Compiler
   │
   ▼
YARV bytecode / InstructionSequence

6. What is bytecode?

Bytecode is an intermediate instruction format designed for a virtual machine.

It is not CPU machine code.

Think of this distinction:

Ruby source
    ↓
Ruby VM bytecode
    ↓
CPU machine code

Bytecode might conceptually contain operations such as:

putself
putobject
send
setlocal
getinstancevariable
leave

These aren’t x86 instructions.

They are instructions understood by the Ruby VM.

Ruby’s documentation exposes the compiled instruction sequence and its bytecode specifically for inspecting how YARV works. (docs.ruby-lang.org)


7. Enter the virtual machine

Now we have something like:

Ruby source
     ↓
Compiler
     ↓
YARV bytecode
     ↓
Ruby VM

The VM executes those instructions.

You can think of it as a machine built inside the Ruby process:

             Ruby Process
┌──────────────────────────────────────┐
│                                      │
│   Ruby VM                            │
│                                      │
│   ┌──────────────────────────────┐   │
│   │ YARV instructions             │   │
│   │                              │   │
│   │ putobject                    │   │
│   │ send                         │   │
│   │ getinstancevariable          │   │
│   │ leave                        │   │
│   └──────────────┬───────────────┘   │
│                  │                   │
│                  ▼                   │
│             VM execution             │
│                                      │
└──────────────────────────────────────┘

CRuby’s interpreter loop and instruction definitions are implemented in the Ruby source tree; the Ruby documentation points to insns.def and vm_exec.c as core pieces of this machinery. (docs.ruby-lang.org)

https://github.com/ruby/ruby/blob/master/vm_exec.c


8. But the VM itself is native code

Here is the important connection to C.

The Ruby VM isn’t written in Ruby.

CRuby itself is implemented primarily in C, with some components implemented in other languages.

So conceptually:

Your Ruby code
      ↓
Ruby bytecode
      ↓
CRuby VM
      ↓
C code
      ↓
Machine instructions
      ↓
CPU

This is where learning C becomes incredibly useful for a Ruby developer.

Ruby is high-level.

The Ruby runtime is much closer to the machine.


9. What happens with our Person class?

Take:

class Person
  def greet
    "Hello, #{@name}"
  end
end

Ruby compiles the class and its methods into VM instruction sequences.

There isn’t simply one giant sequence representing the entire application.

Different constructs can have different instruction sequences.

Ruby’s InstructionSequence#type can identify sequences such as:

:class
:method
:block
:rescue
:ensure
:top

among others. (docs.ruby-lang.org)

Conceptually:

Person class
     │
     ├── class instruction sequence
     │
     ├── initialize method sequence
     │
     └── greet method sequence

When:

person.greet

executes, the VM needs to resolve the method call and execute the corresponding instruction sequence.


10. Method calls become VM work

This Ruby:

person.greet

looks tiny.

Internally, Ruby has to determine:

1. What object is `person`?
2. What class does it belong to?
3. Which method is `greet`?
4. Is the method overridden?
5. What arguments are involved?
6. What execution frame should be created?
7. Which instructions should run?

Conceptually:

person.greet
     │
     ▼
VM method dispatch
     │
     ▼
Find `greet`
     │
     ▼
Create/enter execution frame
     │
     ▼
Execute method instructions

The exact internals are sophisticated, including method caches and object-shape optimizations, but the important thing is that the VM – not your operating system- understands the Ruby method call.


11. Where does the operating system come in?

Eventually, everything has to reach the real machine.

The operating system created the Ruby process.

It provides things such as:

virtual memory
threads
file descriptors
sockets
timers
process scheduling
system calls

When Ruby needs to write:

puts "Hello"

the operation eventually crosses from Ruby runtime code into OS facilities for output.

Conceptually:

puts
 ↓
Ruby implementation
 ↓
C runtime / OS interface
 ↓
system call
 ↓
Operating System
 ↓
terminal / file / pipe

The exact path can vary by platform and implementation, but this is the important architectural boundary.


12. Where does the CPU actually execute instructions?

Here is the complete picture:

┌──────────────────────────────┐
│       Ruby Source            │
│                              │
│  person.greet                │
└──────────────┬───────────────┘
               │
               ▼
┌──────────────────────────────┐
│ Parser / Compiler             │
└──────────────┬───────────────┘
               │
               ▼
┌──────────────────────────────┐
│ YARV Bytecode                │
│ Ruby VM instructions         │
└──────────────┬───────────────┘
               │
               ▼
┌──────────────────────────────┐
│ CRuby VM                     │
│ Native runtime implementation│
└──────────────┬───────────────┘
               │
               ▼
┌──────────────────────────────┐
│ Native Machine Instructions  │
│ x86-64 / ARM64 / etc.        │
└──────────────┬───────────────┘
               │
               ▼
┌──────────────────────────────┐
│ CPU                          │
└──────────────────────────────┘

That is the mental model I want to keep as a Ruby developer.


13. And then there is JIT

The previous diagram describes the interpreter path well, but modern Ruby can go further.

CRuby includes YJIT, a Just-In-Time compiler.

Instead of always executing VM bytecode through the interpreter, frequently executed code can be compiled into native machine code.

Conceptually:

             Ruby source
                  ↓
             VM bytecode
                  ↓
          ┌───────┴────────┐
          │                │
          ▼                ▼
     Interpreter         YJIT
          │                │
          ▼                ▼
      VM execution     Native code
          │                │
          └───────┬────────┘
                  ▼
                 CPU

YJIT became production-ready in Ruby 3.2, and Ruby’s documentation describes the interpreter and YJIT as different execution paths around the VM. (Ruby)

This is an important distinction:

Ruby bytecode is not necessarily the final form of execution.

Depending on how Ruby is running and whether JIT is enabled, execution can involve interpreted VM instructions, JIT-generated native code, or transitions between them.


14. Try it yourself

Check your Ruby implementation:

ruby -v

Check where the executable comes from:

which ruby

Inspect VM instructions:

ruby -e 'p RubyVM::InstructionSequence.compile("1 + 2").disasm'
"== disasm: #<ISeq:<compiled>@<compiled>:1 (1,0)-(1,5)>
0000 putobject_INT2FIX_1_ ( 1)[Li]
0001 putobject 2
0003 opt_plus <calldata!mid:+, argc:1, ARGS_SIMPLE>[CcCr]
0005 leave\n"

Try a method:

ruby -e '
class Person
  def greet
    "hello"
  end
end

puts RubyVM::InstructionSequence.compile(
  "Person.new.greet"
).disasm
'

You will see that Ruby source code has already been transformed into a lower-level instruction sequence before execution.

The exact instructions will depend on your Ruby version, so don’t treat a particular disassembly listing as universal. Ruby explicitly warns that instruction sequences are version-dependent. (docs.ruby-lang.org)


15. The complete mental model

As a senior Ruby developer, I find this model much more useful than simply saying “Ruby is interpreted.”

                   Ruby Program
                        │
                        ▼
                 Ruby Executable
                        │
                        ▼
                    Parser
                        │
                        ▼
                    Compiler
                        │
                        ▼
               YARV Bytecode
                        │
                        ▼
             ┌──────────────────┐
             │     CRuby VM      │
             └────────┬─────────┘
                      │
             ┌────────┴────────┐
             │                 │
             ▼                 ▼
        Interpreter          YJIT
             │                 │
             ▼                 ▼
       Native runtime     Native machine code
             │                 │
             └────────┬────────┘
                      ▼
                  CPU executes
                      │
                      ▼
               Memory / OS / I/O

So when I run:

ruby person.rb

the CPU isn’t magically executing Ruby syntax.

The operating system starts a native Ruby process.

That process parses my Ruby source, compiles it into VM instructions, and the CRuby runtime executes those instructions – potentially compiling hot code to native machine code through JIT.

And that brings us right back to why learning C is so valuable.

When you understand C, pointers, memory, functions, stacks, machine instructions and system calls, the Ruby runtime stops looking like a black box.

It becomes another program.

A very sophisticated program – but still a program running on a machine.

And that is exactly where I want to go next: inside the Ruby object model itself – VALUE, RBasic, object headers, heap allocation and how a simple Person.new becomes a real object in memory.

The natural next article is “What does Person.new actually create inside CRuby?” – connecting the Ruby object model to C structs, VALUE, object headers, heap slots and garbage collection.

Happy Rubying! ~

Build Rails 8 API + React + Vite from Scratch – Part 2

For this specific project, I recommend a single Git repository containing two applications:

rails_react_user_management/
├── backend/      # Rails API
└── frontend/     # React + Vite

This is cleaner than forcing Vite into Rails views because we explicitly want an API-only Rails backend. React’s current guidance supports using Vite as a build tool when building React from scratch, and Vite has a first-class Rails integration, but that integration is more useful when Rails is also serving the frontend. (React)

For our learning project, we’ll therefore keep the frontend and backend clearly separated while keeping them in one repo.

1. Prerequisites

Check:

ruby -v
rails -v
node -v
npm -v

Current Vite requires Node.js 20.19+ or 22.12+. (vitejs)


2. Create the Rails API

mkdir rails_react_user_management
cd rails_react_user_management

rails new backend --api -d postgresql
cd backend

The important part is:

--api

This tells Rails to create an API-only application rather than a traditional Rails application with views/assets. That’s exactly what we want.

Create the database:

bin/rails db:create

Start Rails:

bin/rails server

API:

http://localhost:3000

3. Create our User API

Let’s create a simple User model:

bin/rails generate model User name:string email:string
bin/rails db:migrate

Create controller:

bin/rails generate controller Users

app/controllers/users_controller.rb:

class UsersController < ApplicationController
  def index
    render json: User.all
  end

  def show
    render json: User.find(params[:id])
  end

  def create
    user = User.create!(user_params)
    render json: user, status: :created
  end

  private

  def user_params
    params.require(:user).permit(:name, :email)
  end
end

Routes:

# config/routes.rb

Rails.application.routes.draw do
  scope "/api" do
    resources :users
  end
end

Now:

curl http://localhost:3000/api/users

returns:

[]

Our backend is ready.


4. Create React + Vite frontend

Go back to the root:

cd ..

Create React using Vite:

npm create vite@latest frontend -- --template react
cd frontend
npm install

This creates:

frontend/
├── src/
│   ├── App.jsx
│   └── main.jsx
├── public/
├── index.html
├── package.json
└── vite.config.js

React’s documentation currently recommends a build tool such as Vite when building a React application from scratch and Create React App is deprecated. (React)


5. Start React

npm run dev

You should get:

http://localhost:5173

So now we have:

React/Vite
localhost:5173
↓ HTTP
Rails API
localhost:3000

6. Connect React to Rails

Modify:

// frontend/src/App.jsx

import { useEffect, useState } from "react";

function App() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch("http://localhost:3000/api/users")
      .then(response => response.json())
      .then(data => setUsers(data));
  }, []);

  return (
    <div>
      <h1>Users</h1>

      {users.map(user => (
        <div key={user.id}>
          {user.name} - {user.email}
        </div>
      ))}
    </div>
  );
}

export default App;

But there’s an important issue here:

5173 → 3000

The browser sees these as different origins, so we’ll eventually need CORS or a development proxy.

For development, I prefer the Vite proxy approach.

We can also configure cors from Rails end and make it work:


7. Configure Vite proxy

// frontend/vite.config.js

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],

  server: {
    proxy: {
      "/api": "http://localhost:3000",
    },
  },
});

Now React can simply call:

fetch("/api/users")

instead of:

fetch("http://localhost:3000/api/users")

Vite receives:

GET /api/users

and proxies it to:

http://localhost:3000/api/users

So our architecture becomes:

Browser
   │
   ▼
Vite :5173
   │
   │ /api/*
   ▼
Rails :3000
   │
   ▼
PostgreSQL

8. Seed some users

Let’s add some data.

# backend/db/seeds.rb

User.create!([
  { name: "Abhilash", email: "abhilash@example.com" },
  { name: "John", email: "john@example.com" }
])

Run:

cd backend
bin/rails db:seed

Then:

curl http://localhost:3000/api/users

You should get:

[
  {
    "id": 1,
    "name": "Abhilash",
    "email": "abhilash@example.com"
  },
  {
    "id": 2,
    "name": "John",
    "email": "john@example.com"
  }
]

Refresh React:

http://localhost:5173

and the users should appear.


9. Final project structure

rails_react_user_management/
│
├── backend/
│   ├── app/
│   │   ├── controllers/
│   │   │   └── users_controller.rb
│   │   └── models/
│   │       └── user.rb
│   │
│   ├── config/
│   │   └── routes.rb
│   ├── db/
│   └── Gemfile
│
├── frontend/
│   ├── src/
│   │   ├── App.jsx
│   │   └── main.jsx
│   ├── public/
│   ├── package.json
│   └── vite.config.js
│
└── README.md

10. What we’re learning from this project

We’ll gradually turn this into a proper int.-ready application:

                    React
                      │
             ┌────────┴────────┐
             │                 │
        Components          Hooks
             │                 │
             └────────┬────────┘
                      │
                 API calls
                      │
                      ▼
                Rails API
                      │
             ┌────────┴────────┐
             │                 │
        Controllers       Services
             │                 │
             └────────┬────────┘
                      │
                 ActiveRecord
                      │
                      ▼
                  PostgreSQL

Then we’ll add React Router, reusable components, forms, CRUD, loading/error states, custom hooks, useContext, Redux Toolkit, API abstraction, authentication, pagination, optimistic updates, testing, and production deployment.

For the int., the important architectural distinction is:

Rails is the API/backend and React is the client application. Vite is the frontend development/build tool.

Vite provides the development server and production build pipeline; its current production build uses Rolldown and outputs optimized static assets. (vitejs)

Next, we should implement the actual User Management UI – User list + Add User + Edit + Delete – using proper React components and API calls, because that will give you the hands-on React knowledge needed for the int.

Q) The request inside the useEffect is firing 2 times.
App.jsx line 9: fetch("/api/users") Why?

This is most likely happening because React StrictMode intentionally runs useEffect twice in development to help identify bugs in your components.

The above screenshot shows two successful GET /api/users requests, which matches this behavior.

1. Check main.jsx

Open frontend/src/main.jsx. The Vite React template typically wraps your app in StrictMode:

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.jsx";

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <App />
  </StrictMode>
);

Because of StrictMode, React performs an extra effect setup-and-cleanup cycle when mounting components in development.

our code:

useEffect(() => {
  fetch("/api/users")
    .then(response => response.json())
    .then(data => setUsers(data));
}, []);

Even though the dependency array is empty ([]), the effect runs twice during the initial development mount under StrictMode.

2. Does this happen in production?

No. React’s extra StrictMode effect cycle is development-only. A production build does not perform this extra cycle.

3. Int. takeaway

Remember these three points:

  • useEffect(..., []) normally runs on initial mount, not after every render.
  • StrictMode deliberately runs an extra effect setup-and-cleanup cycle in development.
  • Effects involving network requests should handle cleanup, errors, and cancellation where appropriate.

For our Rails + React application, keep StrictMode enabled. This behavior is expected during development and is not evidence that your Rails API or Vite proxy is incorrectly configured.

📝 Software Documentation Best Practices: How Enterprise Teams Track Code Changes

When working on enterprise applications, developers regularly modify existing modules, add API endpoints, change database schemas, and introduce new business rules.

A task and a pull request help track these changes, but are they enough?

Not always. A developer joining the team six months later should be able to understand how a module works, how an API should be consumed, and why an important architectural decision was made without reading hundreds of historical pull requests.

The goal is not to document every line of code. It is to maintain the knowledge required to understand, operate, and safely change the application.

1. Understand the Different Types of Documentation

Enterprise teams typically maintain several complementary records.

RecordPurposeExample
Task / ticketExplains what needs to change and whyJira ticket describing an order cancellation feature
CommitRecords a code change in version controlAdd order cancellation policy
Pull request (PR)Explains and reviews the implementationChanges to the order service and its tests
Technical documentationExplains how the current system worksOrder lifecycle, module responsibilities
API documentationDefines the API contractParameters, response schema, errors
Architecture Decision Record (ADR)Captures why a significant technical decision was madeWhy Redis was selected for caching
Changelog / release notesDescribes changes included in a releaseNew cancellation feature and bug fixes
RunbookExplains operational proceduresSteps to investigate failed background jobs

These records solve different problems. A PR preserves the history of a change, while technical documentation helps developers understand the current system.

GitHub supports pull request templates to standardize descriptions, testing notes, and links to related issues. GitHub documentation

2. Do We Need to Document Every Code Change?

No. Documentation should be proportional to the impact of the change.

Example: Small bug fix

Suppose you fix a rounding issue in a discount calculation.

You might only need:

  • A ticket describing the defect.
  • A clear PR explaining the correction.
  • An automated regression test.

A separate document would probably add unnecessary overhead.

Example: New payment workflow

Suppose you introduce a new payment authorization and refund workflow.

You may need to update:

  • Module documentation describing the payment lifecycle.
  • API documentation if endpoints or response contracts change.
  • Tests covering authorization, refunds and failure scenarios.
  • An ADR if you introduce a significant architectural decision.
  • Operational documentation if deployments or reconciliation procedures change.

Rule: Document information that future developers, API consumers, operators, or support teams will need. Do not duplicate information that is already obvious from the code, tests, or an existing source of truth.

📁 3. Where Should Documentation Live?

For many Rails projects, keeping technical documentation in the repository makes it easy to review and version alongside code.

An example structure:

rails_react_app/
├── app/
├── spec/
├── db/
│   └── migrate/
├── docs/
│   ├── architecture/
│   │   └── overview.md
│   ├── decisions/
│   │   └── 0001-use-redis-for-cache.md
│   ├── modules/
│   │   ├── orders.md
│   │   └── payments.md
│   ├── api/
│   │   └── openapi.yaml
│   └── runbooks/
│       ├── deployment.md
│       └── failed-jobs.md
├── .github/
│   └── pull_request_template.md
├── README.md
└── Gemfile

This is an example, not a mandatory Rails convention. A small project might need only a README and an API specification. Larger systems may use a dedicated documentation platform, especially when documentation is intended for external customers.

The important requirement is that documentation has a clear owner, a discoverable location, and a process for keeping it current.

🔄 4. What Should the Development Workflow Look Like?

Consider a new feature that allows customers to cancel eligible orders.

Step 1: Create the ticket

The ticket should explain the business requirement and acceptance criteria.

Feature: Cancel an eligible order
Requirements:
- Customers can cancel orders before shipment.
- Shipped orders cannot be cancelled.
- Successful cancellation updates the order status.
- The customer receives a confirmation.

This describes the expected behavior, not the implementation details.

Step 2: Implement the feature

The developer updates the appropriate Rails models, service objects, controllers, jobs, and tests.

For example:

class Orders::Cancellation
  def initialize(order:)
    @order = order
  end

  def call
    return false unless @order.pending?

    @order.update!(status: :cancelled)
  end

  private

  def order
    @order
  end
end

The example illustrates a business operation; production code should also handle authorization, concurrency, and any payment or inventory side effects required by the business rules.

Step 3: Open a pull request

Link the ticket and explain the important changes.

## Summary
Adds order cancellation for eligible orders.

## Implementation
- Adds cancellation business logic.
- Updates order status.
- Adds regression tests.

## Tests
- [x] RSpec service specs
- [x] Request specs
- [ ] E2E tests, if required

## Impact
- [ ] API contract changed
- [x] Business rules changed
- [ ] Database migration added

## Documentation
- [x] Updated order lifecycle documentation

The template reminds the author to consider documentation without requiring a new document for every PR.

Step 4: Review and merge

The reviewer checks the code, tests, business rules, and any documentation affected by the change. CI validates the required checks before merging.

GitHub also supports protected branches, required status checks, and code ownership rules. GitHub PR management

Step 5: Release and maintain the record

If the feature affects customers, release notes may describe the new capability. If it changes operational procedures, update the runbook.

The ticket and PR remain historical records, while maintained documentation explains the current behavior.

5. How Should APIs Be Documented?

API documentation is especially important when the backend serves a separate React frontend, mobile app or other services.

Suppose Rails exposes:

GET /api/products?page=2&per_page=20

Consumers should know the supported parameters, defaults, response format, error behavior, authentication requirements, and compatibility expectations.

For shared APIs, OpenAPI is a strong default. It defines a machine-readable API contract that can support documentation generation, client generation, and contract validation. See the OpenAPI Specification.

A simplified example:

openapi: 3.1.0
info:
  title: Products API
  version: 1.0.0

paths:
  /api/products:
    get:
      summary: List products
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            minimum: 1
            default: 1
        - name: per_page
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 20
      responses:
        "200":
          description: Products returned successfully
        "401":
          description: Authentication required

The specification must match the actual Rails endpoint. Ideally, keep it under version control and update it in the same PR when a public API contract changes.

Do not rely solely on comments in controllers or undocumented JSON responses.

6. When Should You Use an Architecture Decision Record?

An Architecture Decision Record (ADR) captures the reasoning behind a significant technical choice.

For example, your team decides to use Redis to cache frequently requested product searches.

The code explains how caching was implemented, but may not explain why Redis was selected instead of database caching or in-memory caching.

An ADR can record that reasoning:

# ADR-0001: Use Redis for Product Search Caching

## Status
Accepted

## Context
Product searches generate repeated database queries.

## Decision
Use Redis to cache eligible search results.

## Alternatives
- Database materialized views
- Process-local memory caching

## Consequences
- Reduced database load on cache hits
- Additional Redis infrastructure
- Cache invalidation must be handled correctly

ADRs should be used for meaningful decisions involving architecture, trade-offs, security, reliability, or maintainability, not minor refactoring.

Google’s Architecture Decision Records guidance provides additional examples and recommendations.

🗄️ 7. What About Database Changes and Deployments?

This is an important area that documentation practices can easily overlook.

Rails migrations already provide a version-controlled history of schema changes. For example:

class AddCancelledAtToOrders < ActiveRecord::Migration[7.2]
  def change
    add_column :orders, :cancelled_at, :datetime
  end
end

The migration records the database change. You usually do not need a separate document repeating the migration.

However, significant database changes may require deployment instructions, data backfills, rollback considerations, or coordination between application versions.

For example, adding a non-null column to a very large production table may require a staged rollout rather than a single migration.

Document these operational concerns in the PR, deployment plan, or runbook as appropriate. Rails’ Active Record Migrations guide explains how migrations evolve the database schema.

8. Keep Documentation Useful Over Time

Documentation becomes a liability when it disagrees with the actual code.

Follow these practices:

  • Documentation as code: Version technical documentation with the application where practical.
  • Update with the change: Review documentation in the same PR as the behavior it describes.
  • Assign ownership: Use code owners or named teams for critical module documentation.
  • Avoid duplication: Maintain one authoritative API specification rather than multiple manually maintained copies.
  • Automate validation: Check Markdown links, API specifications, and generated documentation where practical.
  • Protect sensitive information: Never publish credentials, personal data, or internal security details in documentation.
  • Review periodically: Remove obsolete instructions and update operational procedures.

For customer-facing APIs or regulated systems, additional requirements may include formal approvals, versioned release documentation, audit trails, and explicit API deprecation policies.

🎯 Final Takeaway

A well-run enterprise development process does not require a separate document for every code change. It requires each type of information to have an appropriate, discoverable record.

Remember:

  • Ticket: What problem are we solving?
  • Pull request: What did we change, and how did we verify it?
  • Technical documentation: How does the system work today?
  • API specification: How should consumers interact with the API?
  • ADR: Why did we make this important technical decision?
  • Release notes and runbooks: What was released, and how do we operate it?

The best documentation workflow is one in which maintaining the right information is part of completing a change, not a separate task that developers postpone until later.


OpenRouter AI: One API for Multiple AI Models

If you are building AI features into a Rails, Node.js, Python, or any other application, you quickly run into a practical problem:

Which AI model should I use?

OpenAI? Claude? Gemini? DeepSeek? Llama? Mistral?

And what happens when your chosen provider is expensive, rate-limited, unavailable, or simply not the best model for a particular task?

This is where OpenRouter becomes interesting.

OpenRouter provides a unified API for accessing hundreds of AI models through a single interface. It follows an OpenAI-compatible API style, so applications using the OpenAI SDK can often switch to OpenRouter with very little code change. (OpenRouter)

What is OpenRouter?

Think of OpenRouter as an AI gateway/router sitting between your application and multiple LLM providers.

Instead of:

Your Application
      |
      +----> OpenAI
      |
      +----> Anthropic
      |
      +----> Google
      |
      +----> DeepSeek

you can have:

Your Application
      |
      v
  OpenRouter
      |
      +----> OpenAI
      +----> Anthropic
      +----> Google
      +----> DeepSeek
      +----> Meta
      +----> Other providers

Your application talks to one API, while OpenRouter handles access to the underlying models and providers.

It currently exposes hundreds of models through its API, and the available catalog can be queried programmatically. (OpenRouter)

Why would a developer use it?

The biggest advantage isn’t simply “many models.”

The real advantage is reducing coupling to a single AI provider.

Imagine your Rails application has:

MODEL = "some-expensive-model"

Six months later you discover that another model:

  • performs better for your use case
  • costs less
  • has better latency
  • has higher availability

With a direct provider integration, changing providers can involve SDKs, authentication, request formats, response formats and application-specific code.

With OpenRouter, the model is largely a configuration decision:

MODEL = "provider/model-name"

That makes experimentation much easier.

Practical Example: OpenAI-Compatible API

One of the most useful features is OpenAI API compatibility.

For example, using the OpenAI Ruby client, the important difference is the base_url:

client = OpenAI::Client.new(
  access_token: ENV["OPENROUTER_API_KEY"],
  base_url: "https://openrouter.ai/api/v1"
)

response = client.chat(
  parameters: {
    model: "provider/model-name",
    messages: [
      {
        role: "user",
        content: "Explain Ruby garbage collection."
      }
    ]
  }
)

puts response.dig("choices", 0, "message", "content")

The exact Ruby client API can vary by gem version, but the architectural idea is simple:

Keep your application code mostly unchanged and change the endpoint/model configuration.

OpenRouter officially documents using the OpenAI SDK with its API by changing the baseURL to the OpenRouter endpoint. (OpenRouter)

Which ruby gem to use?

1. The Recommended Path: The Official openai Gem (Drop-in Compatibility)

# AI assistant - OpenAI
gem "openai", "< 2.0"

Because OpenRouter mirrors OpenAI’s API structure, the easiest and most stable approach is to use the popular official-adjacent openai gem. You simply swap out the base_url and pass your OpenRouter API key.

My Current Rails Implementation is given below (Edited)

MODEL = "openrouter/free"
BASE_URL = "https://openrouter.ai/api/v1"
...
...
@api_key = Rails.application.credentials.dig(:openrouter, :api_key)
@client = OpenAI::Client.new(
      api_key: @api_key,
      base_url: BASE_URL
)

While OpenRouter does not maintain an official, first-party SDK exclusively for Ruby, its API is fully OpenAI-compatible. This gives you three simple ways to integrate OpenRouter into a Ruby application

Switching Models Becomes Cheap

Suppose you are evaluating three models:

models = [
  "openai/...",
  "anthropic/...",
  "google/..."
]

You can test the same prompt against different models without building three separate integrations.

This is particularly useful during development.

For example:

Task: Generate SQL query from natural language

Model A → Good accuracy, expensive
Model B → Very good accuracy, cheaper
Model C → Fast, acceptable accuracy

Instead of making a permanent decision immediately, you can benchmark them.

That’s a much better engineering approach than blindly choosing a model because it is popular.

Top models by task

check: https://openrouter.ai/rankings#task-spend

Automatic Fallbacks

This is one of the features I find particularly useful for production systems.

Suppose your primary model is temporarily:

Rate limited
        ↓
Provider outage
        ↓
Model unavailable

OpenRouter can automatically try another model/provider according to your routing configuration. (OpenRouter)

For example:

models: [
"primary-model",
"fallback-model-1",
"fallback-model-2"
]

If the first model fails, OpenRouter can attempt the next one.

This turns your AI integration from:

Application → One AI Provider

into something closer to:

Application
     |
     v
OpenRouter
     |
     +---- Primary
     |
     +---- Fallback
     |
     +---- Another fallback

For production applications, that resilience can be more important than simply having access to many models.

Provider Routing

There is another layer that is easy to overlook.

A model may be available through multiple providers.

OpenRouter can route requests between providers and allows developers to influence routing based on things such as provider order, price, throughput and latency. (OpenRouter)

For example, if your application cares primarily about speed, routing can be configured to prefer higher-throughput providers.

If cost is the priority, you can prioritize price.

That means your architecture can move from:

Use Model X

towards:

Use Model X
through the provider that currently makes the most sense

That is a much more interesting abstraction for production AI systems.

What About Cost?

OpenRouter doesn’t magically make every model free.

The underlying model still has its own pricing.

OpenRouter says it passes through provider pricing while providing unified billing and routing. (OpenRouter)

However, OpenRouter also exposes free models.

For example:

openrouter/free

is available as a free-model option, subject to the applicable limits. (OpenRouter)

This is particularly useful when learning or experimenting.

For example, instead of spending money while learning AI API integration:

Rails App
   ↓
OpenRouter
   ↓
Free/low-cost model

You can first build the feature, understand the API, streaming, prompts and error handling, and only later move to a more capable paid model.

Important: free does not mean unlimited. OpenRouter documents rate limits for free models, and those limits depend on account/credit conditions. (OpenRouter)

🏗️ A Good Architecture for Rails

For a Rails application, I wouldn’t scatter OpenRouter calls throughout controllers.

Instead, create an abstraction:

class AiClient
  def initialize
    @client = OpenAI::Client.new(
      access_token: ENV["OPENROUTER_API_KEY"],
      base_url: "https://openrouter.ai/api/v1"
    )
  end

  def ask(prompt)
    @client.chat(
      parameters: {
        model: ENV.fetch("AI_MODEL"),
        messages: [
          { role: "user", content: prompt }
        ]
      }
    )
  end
end

Then your application does:

response = AiClient.new.ask(
"Summarize this customer feedback"
)

The model becomes configuration:

AI_MODEL=provider/model-name

Now changing the model doesn’t require changing business logic.

That’s the pattern I would recommend for a production Rails application.

Where OpenRouter Makes the Most Sense

I would consider OpenRouter when:

1. You are experimenting with multiple LLMs

You don’t want to build five separate integrations just to compare models.

2. You want provider flexibility

Your application shouldn’t become tightly coupled to one AI company unless there is a strong reason.

3. You need fallback strategies

AI APIs can experience rate limits and provider outages. Model/provider fallback can improve resilience. (OpenRouter)

4. You are cost-conscious

You can compare models and route workloads according to cost/performance requirements.

5. You are building an AI abstraction layer

For example:

Rails Application
       |
       v
    AiClient
       |
       v
   OpenRouter
       |
   +---+---+---+
   |   |   |   |
  GPT Claude Gemini DeepSeek

Your business logic doesn’t need to know which provider actually processed the request.

Should You Always Use OpenRouter?

No.

There are situations where going directly to the provider makes more sense.

For example, if your application is deeply dependent on provider-specific features, you may want the official SDK/API directly.

Also, adding another layer means you should evaluate:

  • latency
  • provider availability
  • data/privacy requirements
  • supported API features
  • model-specific behavior
  • operational dependencies

OpenRouter also provides controls around provider selection and data collection, including options such as Zero Data Retention routing where supported, so these requirements should be evaluated rather than assumed. (OpenRouter)

My Take as a Senior Developer

I wouldn’t look at OpenRouter simply as “a website where I can access different AI models.”

The more interesting way to think about it is:

OpenRouter is an abstraction layer between your application and the rapidly changing LLM ecosystem.

The AI world is moving extremely fast.

Today’s best model may not be tomorrow’s best model.

If your application is tightly coupled to:

Application → Provider SDK → One Model

you have created an architectural dependency.

If instead you build:

Application
     ↓
AI Service / Adapter
     ↓
OpenRouter
     ↓
Multiple Models / Providers

you gain considerably more flexibility.

For me, model experimentation, provider independence, automatic fallback and a consistent API are the strongest reasons to consider OpenRouter.

And for someone learning AI development, it is also a practical way to experiment with different models without writing a completely different integration for every provider.

🔗 Useful References

Bottom line: If you’re building AI features today, don’t think only about which model to use. Think about how easily you can change that model tomorrow. OpenRouter is one practical way to design for that flexibility.

Happy Development!