Framing the API Boilerplate
I'm now focusing on the specific needs for an API-only Rails application, eliminating view rendering entirely. RSpec will be integrated as the primary testing framework. This sets a solid foundation for the boilerplate's structure and will ensure efficient, focused functionality.
Outlining the Core Elements
I've determined the key components for the API boilerplate. Rails 7.x, with the --api flag, will be the base. PostgreSQL's selected as the database. RSpec, FactoryBot, Faker, Rubocop, and Pry will ensure testing, data generation, code quality, and debugging. I'll use Rails' transaction fixtures for database cleaning.
Planning the Documentation
I'm now outlining a clear, step-by-step guide for users of the API boilerplate. This includes detailed command-line instructions, Gemfile configurations, and RSpec/FactoryBot setups. A simplified example resource and test are being planned to illustrate how the boilerplate can be used effectively. I'm ensuring everything is easy to follow and uses best practices.
Crafting the Implementation Guide
I'm now focusing on the practical steps for users. I've detailed bundle install and rails g rspec:install. Important configurations for FactoryBot, ShouldaMatchers, and JSON parsing will be incorporated. I'm prioritizing Request specs over Controller specs in the example, highlighting modern Rails API practices. I've started working on rails_helper.rb and a RequestHelper module.
Organizing the Final Steps
I'm now focusing on finalizing the output. I'm organizing the guide into key sections: Introduction, CLI commands, Gemfile modifications, configuration files, helper modules (including JSON parsing), and example usage. I'm also adding a README checklist and mentioning rack-cors for API best practices. The goal is to provide a complete and user-friendly guide.
This is a comprehensive boilerplate for a Rails 7+ API using PostgreSQL and RSpec. It follows modern industry standards, prioritizing "Request Specs" (integration tests) over deprecated controller specs.
1. Initialization
Run this command in your terminal. The flags allow us to skip the default testing suite and configure it for API mode implies JSON only.
# -d postgresql: Sets DB to Postgres
# --api: Removes View/Session middlewares
# -T: Skips Minitest (so we can install RSpec)
rails new my_api -d postgresql --api -T
cd my_api
2. Gemfile Setup
Open your Gemfile. We will add RSpec, FactoryBot (for test data), Faker, Rubocop (linting), and Shoulda Matchers (easier assertions).
Add/Update the development and test groups:
# Gemfile
group :development, :test do
# Testing framework
gem 'rspec-rails', '~> 6.0'
# Test data generation
gem 'factory_bot_rails'
# Fake data generator
gem 'faker'
# Linter
gem 'rubocop-rails', require: false
# Debugging
gem 'pry-rails'
end
group :test do
# One-liner matchers (e.g. is_expected.to validate_presence_of)
gem 'shoulda-matchers'
# Database cleaning strategies
gem 'database_cleaner-active_record'
end
# Uncomment rack-cors if you are connecting a Frontend framework (React, Vue, etc)
# gem "rack-cors"
Run the installer:
bundle install
rails generate rspec:install
3. RSpec Configuration
We need to wire up FactoryBot and Shoulda Matchers.
Open spec/rails_helper.rb and configure the RSpec.configure block and add the Shoulda Matchers configuration at the bottom.
# spec/rails_helper.rb
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
# Add this line to specific Custom Helpers later
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
abort e.to_s.strip
end
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
# --- ADD THIS SECTION: FactoryBot Syntax ---
# Allows using `create(:user)` instead of `FactoryBot.create(:user)`
config.include FactoryBot::Syntax::Methods
end
# --- ADD THIS SECTION: Shoulda Matchers Config ---
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
4. Helper for JSON Parsing
In API testing, you constantly parse our response.body. Let's make a helper.
Create spec/support/request_helpers.rb:
module RequestHelpers
def json
@json ||= JSON.parse(response.body)
end
end
Now include it in your spec/rails_helper.rb inside the RSpec.configure block:
RSpec.configure do |config|
# ... previous configs
config.include RequestHelpers, type: :request
end
5. CORS Configuration (Optional but likely needed)
If you uncommented rack-cors in the Gemfile, configure it to allow requests from your frontend.
File: config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*' # Change this to 'http://localhost:3000' in production
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
6. Example Implementation
Here is how to create a resource and test it with this boilerplate.
1. Generate a Scaffold
rails g scaffold Article title:string body:text
rails db:create db:migrate
2. Define a Factory
File: spec/factories/articles.rb
FactoryBot.define do
factory :article do
title { Faker::Book.title }
body { Faker::Lorem.paragraph }
end
end
3. Write the API Request Spec
This looks different than old controller specs. We actually hit the router.
File: spec/requests/articles_spec.rb
require 'rails_helper'
RSpec.describe "Articles", type: :request do
# Initialize test data
let!(:articles) { create_list(:article, 10) }
let(:article_id) { articles.first.id }
describe 'GET /articles' do
before { get '/articles' }
it 'returns articles' do
expect(json).not_to be_empty
expect(json.size).to eq(10)
end
it 'returns status code 200' do
expect(response).to have_http_status(200)
end
end
describe 'GET /articles/:id' do
before { get "/articles/#{article_id}" }
context 'when the record exists' do
it 'returns the article' do
expect(json).not_to be_empty
expect(json['id']).to eq(article_id)
end
it 'returns status code 200' do
expect(response).to have_http_status(200)
end
end
context 'when the record does not exist' do
let(:article_id) { 100 }
it 'returns status code 404' do
expect(response).to have_http_status(404)
end
end
end
describe 'POST /articles' do
let(:valid_attributes) { { article: { title: 'Learn Rails', body: 'Great framework' } } }
context 'when the request is valid' do
before { post '/articles', params: valid_attributes }
it 'creates a article' do
expect(json['title']).to eq('Learn Rails')
end
it 'returns status code 201' do
expect(response).to have_http_status(201)
end
end
context 'when the request is invalid' do
before { post '/articles', params: { article: { title: '' } } }
it 'returns status code 422' do
expect(response).to have_http_status(422)
end
end
end
end
7. Running the Tests
Finally, run your specs to ensure everything is green.
bundle exec rspec
Summary of Structure
Your application structure for testing will now look like this:
spec/
├── factories/ # FactoryBot definitions
│ └── articles.rb
├── fixtures/ # (Ignored/Unused usually)
├── models/ # Unit tests for models
│ └── article_spec.rb
├── requests/ # Integration tests (The meat of API testing)
│ └── articles_spec.rb
├── support/ # Helper modules
│ └── request_helpers.rb
├── rails_helper.rb # Rails-specific config
└── spec_helper.rb # Generic RSpec config