# Step 1: Generate the Rails API app (no scaffold, no Minitest)
rails new my_api --api --database=postgresql --skip-test --skip-javascript --skip-sprockets
cd my_api
Step 2: Update Gemfile
Replace your Gemfile with this (adds RSpec, FactoryBot, Shoulda Matchers, and common API utils like doorkeeper for optional auth, cors, etc.):
# frozen_string_literal: true
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '3.1.2' # or your preferred version
gem 'rails', '~> 7.0.4'
gem 'pg', '~> 1.1'
gem 'puma', '~> 5.0'
gem 'bootsnap', '>= 1.4.4', require: false
# API essentials
gem 'rack-cors'
# Optional: Authentication (JWT example)
gem 'doorkeeper'
gem 'jwt'
group :development, :test do
gem 'debug', platforms: %i[mri mingw x64_mingw]
gem 'rspec-rails', '~> 6.0'
gem 'factory_bot_rails'
gem 'shoulda-matchers', '~> 5.0'
end
group :development do
gem 'listen', '~> 3.3'
end
group :test do
gem 'database_cleaner-active_record'
gem 'simplecov', require: false
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: %i[mingw mswin x64_mingw jruby]
Run:
bundle install
rails generate rspec:install
rails db:create db:migrate
Step 3: Configure RSpec (spec/rails_helper.rb)
Replace spec/rails_helper.rb with this:
# frozen_string_literal: true
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require 'rspec/rails'
require 'factory_bot_rails'
require 'shoulda/matchers'
require 'database_cleaner/active_record'
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
RSpec.configure do |config|
config.fixture_paths = [Rails.root.join('spec/fixtures_files')]
config.use_transactional_fixtures = false
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
config.include FactoryBot::Syntax::Methods
# Shoulda Matchers
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.around(:each) do |example|
DatabaseCleaner.cleaning do
example.run
end
end
end
Step 4: API Configuration
config/application.rb (add these lines after module MyApi):
config.api_only = true
config.generators do |g|
g.test_framework :rspec, fixture: false
g.fixture_replacement :factory_bot, dir: 'spec/factories'
end
config/initializers/cors.rb (create this file):
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*' # Restrict in production!
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
config/routes.rb (example API namespace):
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :posts, only: %i[index show create update destroy]
end
end
end
Step 5: Example Model (app/models/post.rb)
class Post < ApplicationRecord
validates :title, presence: true
validates :body, presence: true
end
Run migration:
rails generate migration CreatePosts title:string body:text
rails db:migrate
Step 6: Example Controller (app/controllers/api/v1/posts_controller.rb)
module Api
module V1
class PostsController < ApplicationController
before_action :set_post, only: %i[show update destroy]
def index
@posts = Post.all
render json: @posts
end
def show
render json: @post
end
def create
@post = Post.new(post_params)
if @post.save
render json: @post, status: :created
else
render json: { errors: @post.errors.full_messages }, status: :unprocessable_entity
end
end
def update
if @post.update(post_params)
render json: @post
else
render json: { errors: @post.errors.full_messages }, status: :unprocessable_entity
end
end
def destroy
@post.destroy
head :no_content
end
private
def set_post
@post = Post.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :body)
end
end
end
end
Step 7: Factories (spec/factories/posts.rb)
FactoryBot.define do
factory :post do
sequence(:title) { |n| "Title #{n}" }
sequence(:body) { |n| "Body #{n}" }
end
end
Step 8: RSpec Tests
Model Spec (spec/models/post_spec.rb):
require 'rails_helper'
RSpec.describe Post, type: :model do
it { should validate_presence_of(:title) }
it { should validate_presence_of(:body) }
it 'has a valid factory' do
post = FactoryBot.build(:post)
expect(post).to be_valid
end
end
Request Spec (spec/requests/api/v1/posts_spec.rb):
require 'rails_helper'
RSpec.describe 'Api::V1::Posts', type: :request do
describe 'GET /api/v1/posts' do
let!(:posts) { create_list(:post, 3) }
it 'returns a successful response' do
get '/api/v1/posts'
expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body).size).to eq(3)
end
end
describe 'POST /api/v1/posts' do
let(:valid_attributes) { { title: 'New Post', body: 'Content' } }
it 'creates a new post' do
post '/api/v1/posts', params: { post: valid_attributes }
expect(response).to have_http_status(:created)
expect(Post.count).to eq(1)
end
end
end
Step 9: Run Tests
# Run all specs
bundle exec rspec
# With coverage
SIMPLECOV=1 bundle exec rspec
Optional: Add Authentication (Doorkeeper + JWT)
- Run
rails generate doorkeeper:install and configure as needed.
- Add
doorkeeper_for :api in controllers.
- Test with tokens in request specs.
This boilerplate is production-ready minimal, fully tested, and extensible. Scale by adding serializers (e.g., blueprinter), pagination (kaminari), etc. For full auth, expand on Doorkeeper. Questions? Ask! 🕵️