Create Task Manager app: Implement – Registration and Login APIs, Setup JSON Serializer

Let’s move to actual authentication APIs. We’ll implement Registration first, then Login. Keeping them separate will make it easier to understand password verification, JWT issuance and refresh-token management.

Step 4.3.1 – User Registration API

Our first endpoint, First authentication endpoint POST /api/v1/auth/register

1. Understand the registration flow

For this step, registration will create the User but won’t issue a JWT.

Why? We’ll implement login separately. Registration and authentication are different operations, even though some applications combine them.

2. Create the controller

Create these directories and file:

mkdir -p app/controllers/api/v1

touch app/controllers/api/v1/registrations_controller.rb

Controller: Api::V1::RegistrationsController

It should inherit from ApplicationController.

Implement one action: create

What should the action do?

A. Accept only permitted parameters

We should allow: email
password
password_confirmation

Never permit: password_digest
admin
role
account_status

The user must not be able to assign protected attributes through registration. Rails API applications include strong parameters and controller callbacks such as before_action through ActionController::API.

B. Create the user – Use the User model and handle validation failures.

C. Successful response – Return HTTP 201 Created.

Response contract:

{
  "user": {
    "id": 1,
    "email": "user@example.com"
  }
}

Important: Explicitly serialize only the allowed attributes. Don’t return user.as_json indiscriminately, because that could expose password_digest.

D. Failed response

Return HTTP 422 Unprocessable Entity.

Example:

{
  "errors": [
    "Email has already been taken"
  ]
}

Use the model’s validation errors rather than constructing your own validation logic in the controller.

3. Configure the API route

Open: backend/config/routes.rb

Add: POST /api/v1/auth/register

It should route to: Api::V1::RegistrationsController#create

Verify it: bin/rails routes

4. Write RSpec request specs

Create:

mkdir -p spec/requests/api/v1

touch spec/requests/api/v1/registrations_spec.rb

Use this structure:

RSpec.describe "API V1 Registration", type: :request do
  describe "POST /api/v1/auth/register" do
    # Examples
  end
end

Implement these five scenarios:

ScenarioExpected result
Valid registration201 Created
Duplicate email422 Unprocessable Entity
Missing email422 Unprocessable Entity
Missing password422 Unprocessable Entity
Malicious mass-assignment attributesProtected attributes ignored

Important security test

Imagine someone sends:

{
  "user": {
    "email": "attacker@example.com",
    "password": "password@1",
    "password_confirmation": "password@1",
    "password_digest": "attacker-controlled-value"
  }
}

Your controller must not permit password_digest. Verify that Rails generates the actual bcrypt digest from the submitted password instead. Also verify that the response does not contain password_digest. This is precisely the type of issue you might encounter in a Rails API controller security-review int.

5. Rate limiting – we’ll introduce it with Login

We’ll add rate limiting to the login endpoint because preventing password brute-force attempts is especially important.

Rails 8.1 provides:

rate_limit to: 10, within: 3.minutes, only: :create

By default, Rails scopes this limit by client IP and uses an ActiveSupport cache store. Exceeding the limit produces HTTP 429. We’ll also cover custom JSON responses for rate-limit failures.

6. Run and verify

Start Rails: bin/rails server -p 3000

You can manually test using curl:

curl -i -X POST http://localhost:3000/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "user": {
      "email": "test@example.com",
      "password": "password@1",
      "password_confirmation": "password@1"
    }
  }'

Run RSpec:

bundle exec rspec spec/requests/api/v1/registrations_spec.rb

Step 4.3.2 – Login API

We’ll implement: POST /api/v1/auth/login

We’ll cover has_secure_password, authenticate, login rate limiting, refresh-token generation and cookie security.

Introducing JSON serializer: Blueprinter

I recommend using Blueprinter for our Rails API. It fits our application well, and I would introduce it now rather than building custom JSON serialization throughout our controllers.

We’ll also fix your registration implementation and request specs.

Blueprinter is a declarative JSON serialization library. It converts Ruby objects and ActiveRecord records into controlled JSON representations.
Github: https://github.com/procore-oss/blueprinter
Documentation: https://www.rubydoc.info/gems/blueprinter

Its main features are:

FeatureBenefit
Explicit fieldsControl exactly what the API exposes
ViewsDifferent response representations for different use cases
AssociationsSerialize related objects
Conditional fieldsInclude fields based on conditions
RenamingCustomize JSON attribute names
Collection renderingSerialize arrays and ActiveRecord relations

It also provides render_as_hash, which is useful when integrating with Rails controllers.

Is it actually fast?

Blueprinter is designed for performance, but I wouldn’t claim it is universally the fastest serializer.

For context, an older Rails 6.1/Ruby 2.7 benchmark found Blueprinter competitive with Alba and Panko, but the results depend on the workload and environment.

Three reasons to retaining Blueprinter for our project:

  1. Strong adoption relative to the alternatives.
  2. Explicit field definitions, views and association support.
  3. Enough flexibility for our User and Task API responses without introducing unnecessary complexity.

For our custom REST API, Blueprinter offers a good balance of readability, performance and maintainability.

Install Blueprinter

In backend/Gemfile, add: gem "blueprinter", "~> 1.3"

Then: cd backend
bundle install

The current RubyGems release listed is 1.3.0, and its declared minimum Ruby version is 3.1, so it meets our project’s declared Ruby requirement.

Create UserBlueprint

Create the directory and file:

mkdir -p app/blueprints

touch app/blueprints/user_blueprint.rb

Add:

class UserBlueprint < Blueprinter::Base
  identifier :id

  fields :email
end

Why only id and email?

Our User database record contains sensitive attributes. For example:

User
├── id
├── email
├── password_digest
├── created_at
└── updated_at

We only want:

{
  "id": 1,
  "email": "test@example.com"
}

This is an important security practice: explicitly whitelist fields for API serialization. Never serialize the entire ActiveRecord object. Blueprinter’s identifier and fields declarations give us control over exactly what is returned.

backend/app/controllers/api/v1/registrations_controller.rb:

class Api::V1::RegistrationsController < ApplicationController
  rate_limit to: 10, within: 3.minutes, only: :create

  def create
    user = User.new(registration_params)

    if user.save
      render json: UserBlueprint.render_as_hash(user, root: :data), status: :created
    else
      render json: { errors: user.errors.full_messages }, status: :unprocessable_entity
    end
  end

  private

  def registration_params
    params.require(:user).permit(:email, :password, :password_confirmation)
  end
end

Understand render_as_hash

Blueprinter offers different rendering methods:

MethodReturns
renderJSON string
render_as_hashRuby Hash
render_as_jsonJSONified Ruby Hash

We use: UserBlueprint.render_as_hash(user, root: :data)

This returns a Ruby Hash:

{
  data: {
    id: 1,
    email: "test@example.com"
  }
}

Rails then handles JSON encoding through: render json: ..., status: :created

One subtle but important point: avoid passing the JSON string returned by UserBlueprint.render into render json:. Rails could encode that string as another JSON string. render_as_hash avoids that issue.

Our API response contract

Successful registration – 201 Created

{
  "data": {
    "id": 1,
    "email": "test@example.com"
  }
}

Failed registration – 422 Unprocessable Entity

{
  "errors": [
    "Email has already been taken"
  ]
}

backend/spec/requests/api/v1/registrations_spec.rb:


require "rails_helper"

RSpec.describe "API V1 Registration", type: :request do
  let(:endpoint) { "/api/v1/auth/register" }

  let(:valid_params) do
    {
      user: {
        email: "test@example.com",
        password: "password@1",
        password_confirmation: "password@1"
      }
    }
  end

  describe "POST /api/v1/auth/register" do
    context "with valid attributes" do
      it "creates a user and returns 201 Created" do
        expect {
          post endpoint, params: valid_params, as: :json
        }.to change(User, :count).by(1)

        expect(response).to have_http_status(:created)

        user = User.find_by!(email: "test@example.com")

        expect(response.parsed_body).to eq(
          {
            "data" => {
              "id" => user.id,
              "email" => user.email
            }
          }
        )

        expect(user.authenticate("password@1")).to be_truthy
      end
    end

    context "with invalid attributes" do
      it "rejects duplicate email" do
        create(:user, email: "test@example.com")

        expect {
          post endpoint, params: valid_params, as: :json
        }.not_to change(User, :count)

        expect(response).to have_http_status(:unprocessable_entity)

        expect(response.parsed_body["errors"])
          .to include("Email has already been taken")
      end

      it "rejects email with different casing" do
        create(:user, email: "test@example.com")

        params = valid_params.deep_merge(
          user: { email: "TEST@EXAMPLE.COM" }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unprocessable_entity)

        expect(response.parsed_body["errors"])
          .to include("Email has already been taken")
      end

      it "rejects missing email" do
        params = valid_params.deep_merge(
          user: { email: nil }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unprocessable_entity)

        expect(response.parsed_body["errors"])
          .to include("Email can't be blank")
      end

      it "rejects missing password" do
        params = valid_params.deep_merge(
          user: {
            password: nil,
            password_confirmation: nil
          }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unprocessable_entity)

        expect(response.parsed_body["errors"])
          .to include("Password can't be blank")
      end

      it "rejects password confirmation mismatch" do
        params = valid_params.deep_merge(
          user: { password_confirmation: "wrong-password" }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unprocessable_entity)

        expect(response.parsed_body["errors"])
          .to include("Password confirmation doesn't match Password")
      end
    end

    context "with malicious mass-assignment attributes" do
      it "does not allow password_digest to be assigned" do
        attacker_digest = SecureRandom.hex(32)

        params = valid_params.deep_merge(
          user: { password_digest: attacker_digest }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:created)

        user = User.find_by!(email: "test@example.com")

        expect(user.password_digest).not_to eq(attacker_digest)
        expect(user.authenticate("password@1")).to be_truthy

        expect(response.parsed_body.dig("data").keys)
          .to contain_exactly("id", "email")
      end
    end
  end
end

Important testing concepts in this spec

1. change(User, :count).by(1) – This verifies the database side effect, not just the HTTP response.

2. as: :json – This tells Rails that we’re sending a JSON request. It also helps test the actual JSON API contract.

3. response.parsed_body – Avoid manually parsing JSON with JSON.parse(response.body) when Rails already provides this helper.

4. deep_merge – Preserves the nested user structure when overriding individual attributes.

5. contain_exactly – Verifies the serialized response contains exactly the permitted attributes, irrespective of ordering.

project structure

Our backend now has:

backend/
├── app/
│   ├── blueprints/
│   │   └── user_blueprint.rb
│   │
│   ├── controllers/
│   │   └── api/
│   │       └── v1/
│   │           └── registrations_controller.rb
│   │
│   └── models/
│       ├── user.rb
│       └── task.rb
│
├── config/
│   └── routes.rb
│
└── spec/
    └── requests/
        └── api/
            └── v1/
                └── registrations_spec.rb

Run: bundle exec rspec spec/requests/api/v1/registrations_spec.rb
Then: bundle exec rspec

API documentation – absolutely, we should have it

I strongly recommend documenting our API using the OpenAPI Specification

Why?

Imagine another developer joins your project. They shouldn’t need to read all your Rails controllers to understand the API. Documentation should tell them:

  • Available endpoints.
  • HTTP methods.
  • Required request parameters.
  • Request and response JSON structures.
  • Authentication requirements.
  • HTTP status codes.
  • Validation errors.
  • Pagination and filtering parameters.

A frontend developer can understand this without knowing anything about Rails.

OpenAPI is a machine-readable contract that describes these API operations, parameters, schemas, security requirements and responses.

Official standard: https://spec.openapis.org/oas/latest.html

rspec-openapi

Generates OpenAPI from existing RSpec request specs. Requires a separate documentation UI.

My recommendation: rspec-openapi + Swagger UI

rspec-openapi – 0.36.0 · November 1, 2026

It generates OpenAPI specifications directly from existing RSpec request specs without requiring a special testing DSL.

It has approximately 3.63 million RubyGems downloads and supports OpenAPI 3.0, 3.1 and 3.2. GitHub repository

Swagger UI – Documentation presentation

Displays the generated OpenAPI file as interactive documentation, including endpoint descriptions, parameters, schemas and request testing. Swagger UI website

How will this work?

For example, when we write:

describe "POST /api/v1/auth/register" do
  it "creates a user" do
    post "/api/v1/auth/register",
      params: valid_params,
      as: :json

    expect(response).to have_http_status(:created)
  end
end

We can run: OPENAPI=1 bundle exec rspec

The tool generates:

doc/
└── openapi.yaml

The generated specification can then be loaded by Swagger UI.

One useful feature is that rspec-openapi preserves manual modifications when updating generated documentation. This matters because generated schemas sometimes need human refinement.

Our final tooling decisions

Rails API tooling baseline

ConcernSelected tool
SerializationBlueprinter
API specificationOpenAPI 3.2
Documentation generationrspec-openapi
Documentation UISwagger UI
Backend testingRSpec
Test dataFactoryBot
AuthenticationJWT + opaque refresh token

When should we introduce API documentation?

I’d introduce rspec-openapi after completing our first few request specs. That way, we won’t create documentation for endpoints that are still changing.

Our learning sequence will now be:

  1. Complete registration API and its request specs.
  2. Implement login, JWT response and refresh-token cookie.
  3. Add authenticated Task CRUD endpoints.
  4. Introduce rspec-openapi and generate our first OpenAPI document.
  5. Configure Swagger UI.
  6. Update documentation whenever request contracts change.
  7. Add API documentation generation and validation to GitHub Actions CI.

This also gives us an excellent engineering practice: API tests become part of our API documentation workflow.

Create Task Manager app: Implement – Rails API, JWT Authentication

In this session let’s get into our applications Authentication section where we decided to move on with JWT token. Here I state that the decision of moving with JWT token is solely for my experience purpose where I already have implemented the token based applications.

The best fit for our application’s authentication system is the Opaque token based authentication. But when we create big applications which has many services connected together and need to be compatible with different platforms/hardwares, jwt is the key for the centralized authentication system.

Step 4.1 – Rails API structure and first endpoint

Before building Task CRUD endpoints, let’s establish our API structure and see how Rails handles HTTP requests.

One important decision: We’ll implement JWT authentication before exposing task data. I don’t want to build an endpoint that returns every user’s tasks and later re-fit authorization.

Understand our API structure

We’ll use versioned API namespaces.

backend/
├── app/
│   ├── controllers/
│   │   ├── application_controller.rb
│   │   └── api/
│   │       └── v1/
│   │           └── authentication_controller.rb
│   │
│   ├── models/
│   │   ├── user.rb
│   │   └── task.rb
│   │
│   └── ...
│
├── config/
│   └── routes.rb
│
└── spec/
    ├── models/
    └── requests/
        └── api/
            └── v1/

Why version the API?

Suppose we eventually release our API to external consumers. We might introduce breaking changes in the future.

/api/v1/tasks
/api/v2/tasks

We can maintain both versions during a migration rather than breaking existing clients.

Understand JWT architecture

JWT stands for JSON Web Token. It is a compact format for securely transmitting claims between parties.

A JWT consists of three parts:

Header example

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload example

{
  "sub": "42",
  "iss": "task_manager_api",
  "aud": "task_manager_web",
  "iat": 1795000000,
  "exp": 1795000600,
  "jti": "unique-token-id"
}

Signature: Generated using the encoded header, encoded payload and signing secret. It allows Rails to detect token modification.

The complete token looks like: xxxxx.yyyyy.zzzzz

Each part is Base64URL encoded, and the signature is cryptographically generated.

Important: JWT is not encrypted by default. Anyone who obtains a JWT can decode its header and payload. The signature protects integrity, not confidentiality. Never put passwords or sensitive personal information in the payload.

Understand the claims we will use

Claims are the information carried inside the JWT payload.

ClaimMeaningOur usage
subSubjectUser ID
issIssuerOur Rails API
audAudienceOur React application
iatIssued atToken creation time
expExpirationToken expiry
jtiJWT IDUnique token identifier

Two important concepts:

sub – Subject – Identifies the user associated with the token.

We’ll use: {
"sub": "42"
}

When Rails receives the token, it can identify user ID 42 after verifying the signature.

exp – Expiration – Defines when the access token expires.

Our initial policy:

10 min – Access token lifetime – Short-lived JWT

7 days – Refresh session lifetime – Initial policy, configurable

We’ll implement refresh-token expiration and rotation separately.

Which signing algorithm should we use?

We’ll start with HS256.

AlgorithmDescription
HS256HMAC using SHA-256 and a shared secret
RS256RSA with SHA-256, using private/public keys
ES256ECDSA with SHA-256

Why HS256?

Our architecture currently has one Rails application that both generates and verifies tokens.

  • Rails has the signing secret.
  • Rails verifies signatures using the same secret.
  • We don’t need public/private key infrastructure yet.

One security rule: the verification algorithm must be explicitly allowlisted. Never trust the alg value supplied in an unverified token header to choose the verification algorithm.

Q) Why use JWT? How we trust the JWT payload/header? JWT vs Opaque token

Read detail here(Premium Content): https://railsdrop.com/why-use-jwt-how-we-trust-the-jwt-payload-header/

Install Ruby JWT gem

We’ll use the official Ruby implementation: https://github.com/jwt/ruby-jwt

From your backend directory: cd backend

Add to your Gemfile:

gem "jwt"

Keep it outside the development/test group because we’ll need it in production too.

Install: bundle install

Verify: bundle info jwt

The gem provides:

JWT.encode(payload, secret, algorithm)
JWT.decode(token, secret, true, algorithm: algorithm)

We’ll use these methods shortly.

Configure the JWT signing secret

This is an important security decision. Never hardcode the JWT secret inside your service class.

Generate a secure secret:

bin/rails secret

Copy the generated value temporarily.

Now edit Rails credentials:

VISUAL="code --wait" bin/rails credentials:edit

Add:

jwt:
  secret_key: YOUR_GENERATED_SECRET

Save and close the editor.

Rails stores credentials encrypted in: config/credentials.yml.enc. The encryption key is stored separately in: config/master.key

The encrypted credentials file can be committed to Git. Never commit master.key. Also, never paste your actual signing secret into our conversation. Later, we’ll configure separate production secrets through deployment/CI environment configuration.

Our authentication service structure

Let’s establish the structure before implementing the login flow.

app/
├── controllers/
│   └── api/
│       └── v1/
│           └── authentication_controller.rb
│
├── services/
│   └── authentication/
│       ├── access_token.rb
│       ├── token_verifier.rb
│       └── refresh_token.rb
│
└── models/
    ├── user.rb
    └── refresh_session.rb

Each component has a separate responsibility.

ComponentResponsibility
AccessTokenGenerate signed JWT
TokenVerifierDecode and verify JWT
AuthenticationControllerLogin, logout and refresh HTTP endpoints
RefreshTokenServiceGenerate, rotate and revoke refresh tokens
RefreshSessionPersist refresh-token session information

We’ll build these individually.

HMAC (Hash-based Message Authentication Code) is a cryptographic technique that combines a secret key and a hash function (such as SHA-256) to verify both the integrity and authenticity of a message.

HS256 (HMAC using SHA-256) is a symmetric cryptographic algorithm used to sign and verify JSON Web Tokens (JWT).

Modified implementation

I want to create a AccessToken class which is clean and not having any constants, error handling code etc. Let’s add a Base class and move the constants and the data which are rarely changes. Also create an Error module in which we store the error related data and will be available across all the classes via mixin.

A. authentication/error.rb

Convert Error into a module.

# frozen_string_literal: true

module Authentication
  module Error
    USER_ERROR = "A persisted user is required"
    SECRET_MISSING = "JWT signing secret is missing"

    def secret_length(length)
      "JWT signing secret must be at least #{length} bytes"
    end
  end
end

Why a module?

We want to reuse error messages and the secret_length helper across authentication classes.

We’ll use extend Error in Base, rather than include Error, because our helper needs to be available in class-method context.

B. authentication/base.rb

Move the common payload generation and secret management here.

# frozen_string_literal: true

require "securerandom"

module Authentication
  class Base
    extend Error

    ALGORITHM = "HS256"
    ISSUER = "task_manager_api"
    AUDIENCE = "task_manager_web"
    ACCESS_TOKEN_TTL = 10.minutes
    SECRET_BYTE_SIZE = 32

    class << self
      def payload
        now = Time.current.to_i

        {
          iss: ISSUER,
          aud: AUDIENCE,
          iat: now,
          exp: now + ACCESS_TOKEN_TTL.to_i,
          jti: SecureRandom.uuid
        }
      end

      private

      def signing_secret
        secret = Rails.application.credentials.dig(:jwt, :secret_key)

        raise KeyError, Error::SECRET_MISSING if secret.blank?

        if secret.bytesize < SECRET_BYTE_SIZE
          raise KeyError, secret_length(SECRET_BYTE_SIZE)
        end

        secret
      end
    end
  end
end

Notice two important things:

  1. payload is now a class method. Subclasses inherit it.
  2. signing_secret is a private class method. Subclasses can use it internally without exposing it as a public API.

C. authentication/access_token.rb

Your AccessToken class becomes much cleaner.

module Authentication
  class AccessToken < Base
    class << self
      def issue(user)
        unless user&.persisted?
          raise ArgumentError, Error::USER_ERROR
        end

        token_payload = payload.merge(sub: user.id.to_s)

        JWT.encode(token_payload, signing_secret, Base::ALGORITHM)
      end
    end
  end
end

This achieves what I wanted:

  • Constants stay in Base.
  • Errors stay in Error.
  • Common payload generation stays in Base.
  • AccessToken only handles access-token generation.

Also, sub is now a string, as required for the JWT Subject claim.

Q) Error: NameError:
uninitialized constant #<Class:Authentication::AccessToken>::ALGORITHM
# ./app/services/authentication/access_token.rb:11

When I modified the line:

JWT.encode(token_payload, signing_secret, ALGORITHM) TO
JWT.encode(token_payload, signing_secret, Base::ALGORITHM) it works. Why?

Find the answer here(Premium): https://railsdrop.com/ruby-constant-lookup-inside-a-singleton-class-class-self/

Modified RSpec specifications

I’d keep two spec files. We should test the shared Base functionality separately and test the actual JWT through its public issue method.

A. spec/services/authentication/base_spec.rb

require "rails_helper"

RSpec.describe Authentication::Base do
  describe ".payload" do
    let(:payload) { described_class.payload }

    it "includes the common JWT claims" do
      expect(payload.keys).to include(
        :iss, :aud, :iat, :exp, :jti
      )

      expect(payload).not_to have_key(:sub)
    end

    it "sets the correct issuer and audience" do
      expect(payload[:iss]).to eq("task_manager_api")
      expect(payload[:aud]).to eq("task_manager_web")
    end

    it "sets the expiration relative to issued time" do
      expect(payload[:exp] - payload[:iat]).to eq(10.minutes.to_i)
    end

    it "generates a unique JWT ID" do
      first_payload = described_class.payload
      second_payload = described_class.payload

      expect(first_payload[:jti]).not_to eq(second_payload[:jti])
    end
  end
end

Note: we’re testing the common functionality, not private implementation details.

B. spec/services/authentication/access_token_spec.rb

require "rails_helper"

RSpec.describe Authentication::AccessToken do
  let(:user) { create(:user) }
  let(:secret) { Rails.application.credentials.dig(:jwt, :secret_key) }

  describe ".issue" do
    context "with a persisted user" do
      let(:token) { described_class.issue(user) }

      it "generates a JWT string" do
        expect(token).to be_a(String)
        expect(token.split(".").size).to eq(3)
      end

      it "contains the correct JWT header" do
        _payload, header = JWT.decode(
          token,
          secret,
          true,
          algorithm: described_class::ALGORITHM
        )

        expect(header["alg"]).to eq("HS256")
      end

      it "contains the correct claims" do
        payload, = JWT.decode(
          token,
          secret,
          true,
          {
            algorithm: described_class::ALGORITHM,
            iss: described_class::ISSUER,
            verify_iss: true,
            aud: described_class::AUDIENCE,
            verify_aud: true,
            required_claims: %w[sub iss aud iat exp jti]
          }
        )

        expect(payload["sub"]).to eq(user.id.to_s)
        expect(payload["iss"]).to eq("task_manager_api")
        expect(payload["aud"]).to eq("task_manager_web")
        expect(payload["iat"]).to be_a(Integer)
        expect(payload["exp"] - payload["iat"]).to eq(10.minutes.to_i)
        expect(payload["jti"]).to be_present
      end

      it "generates a different jti for every token" do
        first_token = described_class.issue(user)
        second_token = described_class.issue(user)

        first_payload = JWT.decode(first_token, secret, true, algorithm: "HS256").first
        second_payload = JWT.decode(second_token, secret, true, algorithm: "HS256").first

        expect(first_payload["jti"]).not_to eq(second_payload["jti"])
      end
    end

    context "without a persisted user" do
      it "raises an error when user is nil" do
        expect {
          described_class.issue(nil)
        }.to raise_error(ArgumentError, Authentication::Error::USER_ERROR)
      end

      it "raises an error when user is not persisted" do
        expect {
          described_class.issue(build(:user))
        }.to raise_error(ArgumentError, Authentication::Error::USER_ERROR)
      end
    end
  end
end

The JWT.decode calls explicitly configure HS256 and validate the issuer, audience and required claims. This follows the Ruby JWT library’s verification API.

Why did we remove the Base payload test from AccessToken?

Your original test was:

payload = described_class.send(:payload, user)

There are two problems:

  • payload was an instance method.
  • send bypasses Ruby’s private-method visibility.

We don’t need that approach anymore.

Instead, our AccessToken spec tests the actual generated JWT and inspects its verified payload.

This is a stronger test of the service’s public behaviour.

Final directory structure

app/services/authentication/
├── base.rb
├── error.rb
└── access_token.rb

spec/services/authentication/
├── base_spec.rb
└── access_token_spec.rb

And as I decided, our future refresh-token implementation will be: app/services/authentication/refresh_token.rb

Run the tests

bundle exec rspec spec/services/authentication/

One security note: these tests verify JWT issuance. We haven’t yet implemented incoming token verification, which is where signature trust, expiry, issuer, audience and algorithm allowlisting must all be enforced.

My recommendation: Keep this structure. It is small, maintainable and leaves room for future authentication functionality without turning AccessToken into a large service class.

Next we’ll build Authentication::TokenVerifier using this same architecture.

JWT decoding and verification

1. What exactly are we verifying?

Remember our generated token: header.payload.signature

When Rails receives this token, it must verify:

CheckWhat are we protecting against?
SignatureToken modification or forged token
AlgorithmAlgorithm substitution attacks
Expiration (exp)Use of expired tokens
Issuer (iss)Tokens from an untrusted issuer
Audience (aud)Tokens intended for another application
Issued at (iat)Invalid or future issuance timestamps
Required claimsMissing identity or security information

The Ruby JWT library supports these checks directly through JWT.decode. We must explicitly specify the accepted algorithm.

2. Understand JWT.decode

We’ve already used this in our specs: JWT.decode(token, secret, true, options)

Let’s understand the arguments:

ArgumentMeaning
tokenIncoming JWT string
secretSigning secret
trueEnable signature verification
optionsAlgorithm and claim verification configuration

The return value is: [
decoded_payload,
decoded_header
]

For example: payload, header = JWT.decode(...)

Important: Never do this in production: JWT.decode(token, secret, false)

That disables signature verification. Decoding a token is not the same as trusting it.

3. Create TokenVerifier

Create:

touch app/services/authentication/token_verifier.rb
touch spec/services/authentication/token_verifier_spec.rb

Our intended structure:

app/services/authentication/
├── base.rb
├── error.rb
├── access_token.rb
├── token_verifier.rb
└── refresh_token.rb

We’ll follow your existing design:

module Authentication
  class TokenVerifier < Base
    class << self
      def verify(token)
        # Your implementation
      end
    end
  end
end

Decide what verify should return

I recommend this contract:

InputResult
Valid JWTVerified payload Hash
Expired JWTnil
Invalid signaturenil
Invalid issuernil
Invalid audiencenil
Malformed JWTnil
Missing tokennil

Why return the payload instead of the User object? Because these are separate responsibilities:

  • TokenVerifier verifies cryptographic authenticity and claims.
  • The authentication layer identifies the corresponding User.
  • The authorization layer decides whether that user can access a resource.

This separation will become useful when we implement current_user

Our implementation requirements

Implement Authentication::TokenVerifier.verify(token).

A. Validate the input – Reject missing or blank tokens.

B. Decode and verify the token – Use JWT.decode with:

  • Signature verification enabled.
  • Base::ALGORITHM as the fixed algorithm.
  • Base::ISSUER as the expected issuer.
  • Base::AUDIENCE as the expected audience.
  • Expiration verification enabled.
  • Issued-at verification enabled.
  • Required claims: sub, iss, aud, iat, exp, jti.

Your decoding options should conceptually look like:

{
  algorithm: Base::ALGORITHM,
  iss: Base::ISSUER,
  verify_iss: true,
  aud: Base::AUDIENCE,
  verify_aud: true,
  verify_expiration: true,
  verify_iat: true,
  required_claims: %w[sub iss aud iat exp jti]
}

See the https://github.com/jwt/ruby-jwt for the current option names and behaviour.

C. Return the verified payload

JWT.decode returns an array. We only need the first element. Return the payload after successfully validating the token. Also ensure the sub claim is a non-empty string.

D. Handle JWT errors

An invalid token should not crash our Rails application. For the current ruby-jwt 3.3 error hierarchy, use:

rescue JWT::TokenError
  nil

Version note: JWT::TokenError was introduced in 3.3.0. Older versions can use JWT::DecodeError, which remains a compatible superclass for decoding errors. You can check your installed version using: bundle info jwt

Do not rescue every StandardError. A missing signing secret or an application programming error should not silently become an invalid-token response.

RSpec assignment

Create these examples in: spec/services/authentication/token_verifier_spec.rb

Use:

RSpec.describe Authentication::TokenVerifier do
  describe ".verify" do
    # Your examples
  end
end

Implement these seven scenarios.

TestExpected result
Valid JWT generated by AccessTokenReturns Hash
Correct subjectsub matches User ID
Expired tokenReturns nil
Wrong signing secretReturns nil
Wrong issuerReturns nil
Wrong audienceReturns nil
Malformed token / nil tokenReturns nil

Useful testing hints

For the valid token:

user = create(:user)
token = Authentication::AccessToken.issue(user)

For creating an expired token in your spec, use the same signing secret but give it an expiration timestamp in the past.

For testing an invalid signature, generate a token using a different secret.

For issuer and audience tests, generate tokens with incorrect claims, but sign them using the legitimate application secret. This ensures we’re testing claim validation rather than signature failure.

We don’t need to use mocks or stubs yet. These tests should use real JWT generation and verification.

6. How our authentication flow will eventually work

Notice that successful JWT verification alone doesn’t prove that the user still exists or that their account is active. We’ll implement those checks in the next authentication milestone. Also, we’ll later introduce rate_limit and authorization checks in the relevant controllers.

TokenVerifier implementation

backend/app/services/authentication/token_verifier.rb:

module Authentication
  class TokenVerifier < Base
    class << self
      def verify(token)
        return nil unless token.is_a?(String) && token.present?

        options = {
          algorithm: Base::ALGORITHM,
          iss: Base::ISSUER,
          verify_iss: true,
          aud: Base::AUDIENCE,
          verify_aud: true,
          verify_expiration: true,
          verify_iat: true,
          verify_jti: true,
          required_claims: %w[sub iss aud iat exp jti]
        }

        payload, = JWT.decode(token, signing_secret, true, options)

        return nil unless valid?(payload["sub"])
        return nil unless valid?(payload["jti"])

        payload
      rescue JWT::TokenError
        nil
      end

      private

      def valid?(item)
        item.is_a?(String) && item.present?
      end
    end
  end
end

Why these changes?

CodeResponsibility
token.is_a?(String)Reject unexpected input types
signing_secretReuse secret validation from Base
algorithmOnly accept HS256
verify_issValidate trusted issuer
verify_audValidate intended audience
verify_expirationReject expired tokens
verify_iatReject invalid/future issuance times
verify_jtiVerify JWT ID
required_claimsReject missing claims
valid_subject?Ensure a valid user identifier
valid_jti?Ensure a non-empty token identifier
rescue JWT::TokenErrorConvert invalid JWTs into nil

One important distinction: We only rescue JWT token errors. If our signing secret is missing or misconfigured, the application should raise a configuration error rather than pretending the incoming token is invalid.

Complete RSpec specifications

backend/spec/services/authentication/token_verifier_spec.rb:

require "rails_helper"

RSpec.describe Authentication::TokenVerifier do
  let(:user) { create(:user) }
  let(:secret) { Rails.application.credentials.dig(:jwt, :secret_key) }
  let(:valid_token) { Authentication::AccessToken.issue(user) }

  let(:decoded_payload) do
    JWT.decode(
      valid_token,
      secret,
      true,
      algorithm: Authentication::Base::ALGORITHM
    ).first
  end

  describe ".verify" do
    context "with a valid token" do
      it "returns the verified payload" do
        result = described_class.verify(valid_token)

        expect(result).to be_a(Hash)
        expect(result["sub"]).to eq(user.id.to_s)
        expect(result["iss"]).to eq(Authentication::Base::ISSUER)
        expect(result["aud"]).to eq(Authentication::Base::AUDIENCE)
      end

      it "returns the jti claim" do
        result = described_class.verify(valid_token)

        expect(result["jti"]).to be_present
      end
    end

    context "with an invalid token" do
      it "returns nil for blank tokens" do
        expect(described_class.verify(nil)).to be_nil
        expect(described_class.verify("")).to be_nil
        expect(described_class.verify("  ")).to be_nil
      end

      it "returns nil for non-string input" do
        expect(described_class.verify(123)).to be_nil
      end

      it "returns nil for malformed tokens" do
        expect(described_class.verify("invalid-token")).to be_nil
      end

      it "returns nil for expired tokens" do
        expired_payload = decoded_payload.merge(
          "exp" => 1.minute.ago.to_i
        )

        token = JWT.encode(
          expired_payload,
          secret,
          Authentication::Base::ALGORITHM
        )

        expect(described_class.verify(token)).to be_nil
      end

      it "returns nil for an invalid signature" do
        token = JWT.encode(
          decoded_payload,
          SecureRandom.hex(32),
          Authentication::Base::ALGORITHM
        )

        expect(described_class.verify(token)).to be_nil
      end

      it "returns nil for an incorrect issuer" do
        payload = decoded_payload.merge(
          "iss" => "untrusted_api"
        )

        token = JWT.encode(
          payload,
          secret,
          Authentication::Base::ALGORITHM
        )

        expect(described_class.verify(token)).to be_nil
      end

      it "returns nil for an incorrect audience" do
        payload = decoded_payload.merge(
          "aud" => "another_application"
        )

        token = JWT.encode(
          payload,
          secret,
          Authentication::Base::ALGORITHM
        )

        expect(described_class.verify(token)).to be_nil
      end

      it "returns nil when a required claim is missing" do
        payload = decoded_payload.except("sub")

        token = JWT.encode(
          payload,
          secret,
          Authentication::Base::ALGORITHM
        )

        expect(described_class.verify(token)).to be_nil
      end

      it "returns nil when issued at is in the future" do
        payload = decoded_payload.merge(
          "iat" => 5.minutes.from_now.to_i
        )

        token = JWT.encode(
          payload,
          secret,
          Authentication::Base::ALGORITHM
        )

        expect(described_class.verify(token)).to be_nil
      end
    end
  end
end

We’ll test real token generation and verification rather than mocking JWT.

Run the specifications:

bundle exec rspec spec/services/authentication/token_verifier_spec.rb

Then run both JWT service specs:

bundle exec rspec spec/services/authentication/

Understand an important distinction before our next step

Our verifier returns:

{
  "sub" => "42",
  "iss" => "task_manager_api",
  "aud" => "task_manager_web",
  "iat" => 1795000000,
  "exp" => 1795000600,
  "jti" => "..."
}

It does not return a User object.

The next authentication layer will do: User.find_by(id: payload["sub"])

Why query the database if JWT is self-contained? Because we need to know whether:

  • The user still exists.
  • The account is active.
  • The user has been disabled.

JWT signature verification proves that the token is authentic. It does not guarantee that the associated user is still allowed to access the application.

We’ll implement this in our authentication controller/base controller.

Next milestone: Registration and Login APIs, including password verification with has_secure_password, issuing JWTs, Rails rate_limit and request specs. We’ll also ensure that a user cannot access another user’s tasks by changing an ID.

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

Create the User model

Now let’s start building our actual Rails application.

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

Install bcrypt

Rails provides has_secure_password, which uses bcrypt for password hashing.

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

Why bcrypt?

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

Generate User model

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

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

Review the migration

Make these database-level changes:

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

      t.timestamps
    end

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

Run:

rails db:prepare -t 

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

Checklist

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

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

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

User model, validations and password security

in User model add: has_secure_password

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

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

The behaviour is:

InputResult
Correct passwordReturns the user object
Incorrect passwordReturns false

Important things to understand:

has_secure_password provides these validations automatically:

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

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

Normalize the email address

onsider these inputs:

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

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

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

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

Why use normalizes?

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

Rails has supported normalizes since Rails 7.1.

Add email validations

Add validations for:

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

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

Important architectural distinction:

We’re using two protections for uniqueness:

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

Neither replaces the other.

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

Understand the complete model behaviour

Your model should now have three responsibilities:

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

Prepare RSpec model testing

described_class

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

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

When we write: RSpec.describe User do

described_class refers to User

Why is this useful?

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

Open:backend/spec/models/user_spec.rb

new vs create!

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

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

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

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

RSpec assignment

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

Exercise 1 – Valid user

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

Exercise 2 – Email presence

Test what happens when:

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

Verify the appropriate validation error.

Exercise 3 – Email uniqueness

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

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

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

Because email uniqueness should be case-insensitive.

Exercise 4 – Email normalization

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

Also test that uppercase input is normalized.

Exercise 5 – Password digest

Create a user with a password.

Verify:

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

Exercise 6 – Password authentication

Test both scenarios:

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

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

Exercise 7 – Password confirmation

Try assigning:

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

Verify that the user is invalid.

Remember: Rails only checks confirmation when password_confirmation is supplied.

User Spec spec/models/user_spec.rb:

require 'rails_helper'

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

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

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

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

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

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

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

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

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

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

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

Q): How does let caching work?

This is an important concept.

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

Consider:

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

Now imagine three examples:

it "example 1" do
  user
  user
end

it "example 2" do
  user
end

it "example 3" do
  user
end

The execution looks like this:

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

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

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

So the output will be:

Creating user
Creating user
Creating user

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

What about let!?

Exactly the same memoization, but with eager evaluation.

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

The block executes automatically before every example.

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

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

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

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

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

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

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

What do we actually test in production?

My recommendation is:

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

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

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

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

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

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

How do we decide whether to write a separate test?

I generally follow these principles.

Rule 1: Different behaviour deserves different examples.

For example:

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

These should be separate examples because they represent different outcomes.

Rule 2: Don’t test every framework feature.

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

Rule 3: Test security boundaries thoroughly.

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

Rule 4: Test regressions.

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

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

When is it Performed?

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

What happens when a model becomes bigger?

Imagine our User model eventually supports:

class User < ApplicationRecord
  has_secure_password

  has_many :tasks
  has_many :refresh_sessions

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

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

We organize them by behaviour:

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

Inside:

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

  describe "associations" do
    # Association behaviour
  end

  describe "authentication" do
    # Password authentication
  end

  describe "email normalization" do
    # Normalization behaviour
  end

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

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

What about 100% test coverage?

Don’t chase 100% coverage blindly.

Consider:

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

I prefer meaningful test coverage over a high coverage percentage.

My recommendation for our project

We’ll follow a practical testing strategy.

Our testing strategy

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

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

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

Integration testing: Verify that important application workflows work together.

Introduce FactoryBot

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

FactoryBot setup and fundamentals

1. Why do we need FactoryBot?

Consider our existing RSpec code:

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

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

This creates several problems:

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

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

Install FactoryBot:

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

Open backend/Gemfile. Add:

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

Why both groups?

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

Do: bundle install

Configure FactoryBot with RSpec

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

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

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

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

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

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

Now open: spec/rails_helper.rb

Find this line (it may be commented out):

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

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

Why use spec/support?

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

For example:

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

Create your first factory

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

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

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

    password { "password@1" }
  end
end

Let’s understand each part.

FactoryBot.define – Container for our factory definitions.

factory :user – Defines a factory named user.

FactoryBot automatically identifies the corresponding Rails model as User.

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

For example:

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

Why do we need sequences?

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

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

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

Understand FactoryBot build strategies

This is probably the most important FactoryBot concept.

FactoryBot supports four commonly used strategies.

1. build(:user)

In memory user = build(:user)

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

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

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

2. create(:user)

Persisted user = create(:user)

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

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

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

3. build_stubbed(:user)

Stubbed object user = build_stubbed(:user)

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

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

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

4. attributes_for(:user)

Hash only attributes = attributes_for(:user)

Returns an attribute hash rather than a User object.

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

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

FactoryBot traits and list factories

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

1. List factories: build_list and create_list

Suppose we need five users for a test.

Without list factories:

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

FactoryBot provides a better way.

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

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

MethodObjectsDatabase
build_list5No records
create_list55 records

Both methods return arrays.

Exercise

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

Exercise A – build_list – Create three users and verify:

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

Exercise B – create_list – Create three users and verify:

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

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

FactoryBot traits

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

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

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

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

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

Assignment

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

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

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

Test these traits

In your new spec file, create examples that:

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

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

# spec/models/user_spec.rb

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

Understanding when to use traits vs overrides

This distinction is useful in real projects.

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

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

Create the Task model and database relationship

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

Our first important domain relationship:

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

Database relationship

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

1. Decide our Task attributes

Let’s start with a simple schema.

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

For the status, we’ll eventually support:

  • pending
  • in_progress
  • completed

Why integer?

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

Generate the Task model

From your backend directory:

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

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

Inspect the actual migration and make the necessary adjustments.

Configure the associations

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

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

      t.timestamps
    end
  end
end

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

# task model
class Task < ApplicationRecord
  belongs_to :user
end
 

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

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

FactoryBot associations: User and Task

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

1. Create the Task factory

Open: spec/factories/tasks.rb

Our Task model has:

  • title
  • description
  • status
  • user_id

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

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

    association :user
  end
end

Understand association :user

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

How does FactoryBot handle associated objects?

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

Consider: task = build(:task)

Expected behaviour:

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

Now consider: task = create(:task)

Expected behaviour:

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

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

An important mistake to avoid:

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

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

Attribute override for associations

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

We can override the association:

user = create(:user)

task = build(:task, user: user)

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

RSpec assignment

open: backend/spec/models/task_spec.rb

Use:

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

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

Implement these four examples.

Exercise 1 – Build associated User

Use build(:task). Verify:

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

Exercise 2 – Create associated User

Use create(:task). Verify:

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

Exercise 3 – Override association

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

Exercise 4 – Multiple Tasks for one User

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

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

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

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

Task model validations

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

1. Define our validation requirements

For our application, let’s establish these rules:

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

Why these requirements?

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

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

class Task < ApplicationRecord
  belongs_to :user

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

Write Task model specs

Open: backend/spec/models/task_spec.rb

Organize the tests using:

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

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

Use FactoryBot for test data.

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

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

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

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

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

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

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

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



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

task.user returns a User.

task.user_id matches task.user.id.

Rails Enums

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

1. Why do we need enums?

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

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


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

if task.status == 2
end

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

Define our Task statuses

We’ll support three statuses:

Pending 0 – Task hasn’t been started yet.

In progress 1 – Task is currently being worked on.

Completed 2 – Task has been completed.

Open: backend/app/models/task.rb

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

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

Why use an explicit hash instead of an array?

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

This automatically maps values based on their positions:

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

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

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

Understand what Rails generates automatically

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

A. Predicate methods

You can check the current status:

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

Example:

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

task.pending?
# true

task.completed?
# false

The initial status comes from our database default of 0

Bang methods

Rails generates methods that update and persist the status:

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

For example:

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

task.completed!

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

Scopes

Rails automatically generates scopes:

Task.pending
Task.in_progress
Task.completed

These return ActiveRecord relations. For example: Task.pending

Conceptually generates a query similar to:

SELECT * FROM tasks WHERE status = 0;

You can also use negative scopes: Task.not_completed

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

Reading and updating status

You can assign a status using its symbolic value:

task.status = :completed

Or:

task.update!(status: :in_progress)

Reading the status returns its string representation:

task.status
# "in_progress"

However, the underlying database value is an integer.

Accessing the mapping

Rails also provides:

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

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

Important: What does validate: true do?

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

For example:

task.status = :unknown

But with validate: true:

task.status = :unknown

task.valid?
# false

Rails adds an inclusion validation instead.

Why did we choose this?

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

{
  "status": "invalid_status"
}

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

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

RSpec assignment

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

Add a new group:

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

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

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

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

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

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

Implement these six scenarios.

Exercise 1 – Default status

Build a new Task without specifying its status. Verify:

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

Remember, this depends on the database default being 0.

Exercise 2 – Status assignment

Build a Task with: status: :in_progress Verify:

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

Exercise 3 – Bang methods

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

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

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

Exercise 4 – Enum mapping

Verify the mapping returned by: described_class.statuses

Check that each status maps to the expected integer.

Exercise 5 – Invalid status

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

Because we enabled validate: true, verify that:

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

Also check what happens when status is explicitly assigned nil.

Exercise 6 – Enum scopes

Create three Tasks:

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

Verify that:

Task.pending
Task.in_progress
Task.completed

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

One database configuration check

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

This is important for two reasons:

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

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

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

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

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

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

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

Let’s understand the actual trade-offs.

1. Three ways to store status

There are three approaches worth understanding.

Option A: Store strings directly

Database:

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

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

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

But you need to implement your own validation:

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

And implement any convenience methods or scopes yourself.

Advantages:

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

Option B: Rails integer-backed enum

This is what we’re currently implementing.

Database:

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

Rails model:

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

Rails translates between the integer and its corresponding symbolic value.

For example:

task.status
# "pending"

task.status = :completed

task.save!

task.status
# "completed"

You also get:

task.pending?
task.completed!

Task.pending
Task.completed

These methods and scopes are generated by Rails.

Option C: Rails string-backed enum

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

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

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

task.pending?
task.completed!

Task.pending
Task.completed

But PostgreSQL stores the actual strings.

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

2. Does storing integers improve performance?

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

A. Storage size

PostgreSQL uses:

For our three statuses:

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

Approximate column value storage, excluding row and index overhead.

Imagine you have 10 million tasks.

For illustration, assuming every record has the same status:

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

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

B. Index performance

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

add_index :tasks, :status

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

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

Both can use PostgreSQL B-tree indexes.

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

Consider: SELECT * FROM tasks WHERE status = 0;

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

Both can use an appropriate index.

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

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

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

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

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

3. What is the actual benefit of Rails enums?

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

Without enums, you might write:

task.status == "completed"

Task.where(status: "pending")

And define your own scopes and methods.

With Rails enums:

task.completed?

task.completed!

Task.pending
Task.in_progress
Task.completed

You also get the status mapping through: Task.statuses

So enums provide:

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

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

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

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

Here’s the recommendation.

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

For our project, both are perfectly reasonable.

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

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

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

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

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.

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!

Ruby’s Triple-Dot Operator: Argument Forwarding from 2.7 to 4.0

If you’ve ever written a method whose entire job is to pass its arguments straight through to another method, you’ve felt this pain:

class Repository
def find(id, *args, **kwargs, &block)
connection.find(id, *args, **kwargs, &block)
end
end

Three parameter types, three splat operators, zero information conveyed. Ruby 2.7 solved this with a single token: ...

The problem it solves

... is Ruby’s argument forwarding shorthand. It captures everything passed to a method – positional args, keyword args, and a block – and lets you re-throw it at another method without naming a single one of them.

def find(...)
connection.find(...)
end

Same behavior as the splat version above, minus the noise. It behaves like a bare super with parens: “take what I got, send it onward, unchanged.”

Ruby 2.7: the baseline

... shipped in Ruby 2.7 (Dec 2019) with one hard restriction: it has to be the only parameter in the definition, and the only argument in the call. You can’t mix it with named params, and you can’t inspect or transform the forwarded values.

def log_call(...)
puts "calling..."
perform(...)
end
def perform(*args, **kwargs, &block)
block.call(args, kwargs)
end
log_call(1, 2, k: 3) { |a, k| p [a, k] }
# => [[1, 2], {k: 3}]

Clean, but rigid – useful only for pure pass-through wrappers (logging, memoization, decorators).

Ruby 3.0: leading arguments

Ruby 3.0 (Dec 2020) lifted the “must be alone” rule. You can now peel off one or more leading positional arguments before the ..., in both the definition and the call site:

def method_missing(name, ...)
send(:"do_#{name}", ...)
end

This is the textbook use case – method_missing needs the method name for dispatch logic, but everything else should flow through untouched:

def transform(a, ...)
process(a, ...)
end
def process(a, *args, **kwargs, &block)
[a, args, kwargs]
end
transform(1) # => [1, [], {}]
transform(1, 2, k: 3) # => [1, [2], {k: 3}]

This turned ... from a niche decorator trick into something you’d actually reach for in delegation-heavy code – Rails controllers forwarding to services, DSL builders, proxy objects.

Ruby 3.1: anonymous block forwarding

Ruby 3.1 (Dec 2021) split the block piece out on its own. If you only need to forward the block and want the positional/keyword args handled explicitly, use a bare &:

def perform(&)
execute(&)
end

No name required on either side. This composes with regular named params:

def retry_with(times:, &)
times.times { execute(&) }
end

Ruby 3.2: anonymous splat and double-splat

Ruby 3.2 (Dec 2022) completed the set, adding anonymous * and ** forwarding to match the anonymous & from 3.1:

def split_arguments(*, **)
pass_positional(*) # forwards only positional args
pass_keywords(**) # forwards only keyword args
end
split_arguments(1, 2, a: 3, b: 4)
# pass_positional(1, 2)
# pass_keywords(a: 3, b: 4)

This matters when a method needs to route positional and keyword args to different destinations – ... can’t do that, since it moves as one atomic bundle.

Ruby 3.3 / 3.4 / 4.0: no new syntax, better tooling

No further language changes landed for ... itself through 3.3, 3.4, or Ruby 4.0 (released Dec 2025). Two things worth knowing if you’re on current Ruby:

  • RBS gained first-class support for forwarding parameters in method type signatures in 2026 (def request: (...) -> Response), so type-checked codebases no longer have to erase forwarded signatures to untyped.
  • Ruby 4.0 changed splat semantics slightly: *nil no longer calls nil.to_a, and **nil no longer calls nil.to_hash. It’s not a ...-specific change, but if you forward keyword args that might legitimately be nil (e.g., **opts where opts defaults to nil), check this – it’ll raise instead of silently treating nil as {}.

Version cheat sheet

VersionReleasedAdds
2.7Dec 2019... – forwards all args + block, must be the sole parameter
3.0Dec 2020Leading arguments alongside ...: def foo(a, ...)
3.1Dec 2021Anonymous block forwarding: def foo(&); bar(&); end
3.2Dec 2022Anonymous splat/double-splat: def foo(*, **); bar(*); baz(**); end
3.3 – 4.02023 – 2025No new ... syntax; RBS forwarding types; *nil/**nil semantics changed in 4.0

If you’re targeting older runtimes: 2.7 and 3.0 are long past EOL, 3.1 EOL’d in 2025, and only 3.2+ receives active support as of this writing. Practically, any codebase forwarding arguments today should assume 3.2+ and use whichever granularity (..., &, *, **) fits the delegation.

Where I’d push back on using it

... is DRY, but it’s opaque. def foo(...) tells a reader nothing about the method’s actual contract – they have to chase the call chain to find out what foo accepts. For a pure pass-through utility (logging wrapper, method_missing dispatch, a thin repository shim), that opacity is the whole point and it’s the right call. For a public API boundary – a service object’s entry point, a gem’s documented interface – I’d argue explicit named parameters (or at minimum RBS/Sorbet signatures) win, because the signature is the documentation, and ... erases it at the exact place callers look first.

A second edge case: you can’t currently pass extra trailing arguments after a forwarded ... in a call (bar(extra, ...) is still restricted) – only leading ones. If you need to inject an argument after the forwarded set, you’re back to explicit *args, **kwargs, &block.

Rule of thumb: reach for ... (or &/*/**) at internal delegation boundaries where the wrapper genuinely adds no new arguments of its own. Keep explicit signatures at any boundary another engineer – or a type checker – needs to reason about without reading the delegate.

Happy Rubying!