The user wants a "boilerplate" for a Ruby on Rails API with RSpec testing.
What does "boilerplate" imply in this context?
Command to create the app: The starting point.
Gemfile setup: Essential gems for an API (e.g., rack-cors, active_model_serializers or similar, though standard JSON is often enough now) and testing (rspec-rails, factory_bot_rails, faker, shoulda-matchers, database_cleaner (though often not strictly needed with latest system tests, good to mention or configure)).
Directory Structure: How to organize things (though Rails does this mostly).
Sample Code: A basic scaffold to demonstrate how to write a controller spec or request spec.
Testing Setup: rails_helper.rb and spec_helper.rb configuration details.
Step-by-Step Plan:
Prerequisites: Mention Ruby and Rails versions.
Creation Command: Use rails new ... --api. This is the most crucial step for an API-only app.
Gemfile: Add RSpec, FactoryBot, Faker, Shoulda-Matchers, Rack-CORS, and maybe a JSON serialization gem (like blueprinter or just standard as_json, or active_model_serializers - I'll stick to standard or blueprinter as AMS is a bit legacy/heavy, but actually, for a boilerplate, simple render json: is often best to avoid dependencies. I will include rack-cors and jwt (json web tokens) because most APIs need authentication, or at least mention it. Actually, keeping it simple is better for a generic boilerplate. I'll stick to rspec-rails, factory_bot_rails, faker, shoulda-matchers, simplecov.
Installation: Run the generators.
Configuration:
Uncomment rack-cors in config/initializers/cors.rb.
Configure spec/rails_helper.rb (DatabaseCleaner is usually automatic now in Rails 5+, but I should set up FactoryBot syntax and Shoulda-Matchers).
Example Implementation:
Generate a scaffold (e.g., Post).
Show a request spec (integration test) instead of controller specs (which are discouraged in modern Rails).
Auth (Optional but good): Briefly mention JWT or Devise-API, but maybe just keep it to the request/spec setup to avoid over-complicating the "boilerplate". I will skip full auth implementation but structure it so it's ready.
Drafting the Content:
Command: rails new my_api --api -T (Skip minitest).
Gemfile:
gem 'rack-cors' (uncommented).
group :development, :test: rspec-rails, factory_bot_rails, faker.
Show a request spec example (GET /posts, POST /posts).
Refining the Output:
Make it copy-pasteable where possible. Use clear headings.
Self-Correction during thought process:
Should I include serialization? ActiveModel::Serializer is common but JSONAPI::Serializer or Blueprinter are faster. Since this is a basic boilerplate, render json: resource is sufficient and native. I won't add a serialization gem to keep it lightweight, but I will mention CORS as it's essential for APIs.
What about Docker? A boilerplate often includes a Dockerfile now. I'll add a simple Dockerfile and docker-compose section as "Optional" because it's very popular.
Let's stick to the core request first: Rails API + RSpec.
Final Structure:
Initialize Project: rails new ...
Gemfile: The list of gems.
Configuration:
CORS.
RSpec config (rails_helper.rb).
Example Usage:
Scaffold.
Updated Request Spec (showing how to test).
Let's write it out.
Here is a comprehensive boilerplate guide for creating a Ruby on Rails API optimized for RSpec testing.
This setup assumes you are using Rails 7+ and Ruby 3.1+.
1. Create the Project
Run the standard rails new command with the --api flag. This skips Views, Cookies, Sessions, and CSRF protection, giving you a lighter, middleware-restricted stack. We also skip the default Test::Unit framework (minitest).
bash
rails new my_api_name --api --skip-test
cd my_api_name
2. Configure the Gemfile
Open your Gemfile and add the following gems to the :development, :test and :test groups.
ruby
group :development, :test do
# Standard debugging
gem 'debug', platforms: %i[ mri windows ]
# RSpec core
gem 'rspec-rails', '~> 6.0'
# Replacement for fixtures (generates fake data)
gem 'factory_bot_rails'
# Generates fake data (names, emails, etc.)
gem 'faker'
end
group :test do
# Cleans the database between tests
gem 'database_cleaner-active_record'
# One-liners for testing common functionality (validations, associations)
gem 'shoulda-matchers', '~> 5.0'
# Code coverage analysis
gem 'simplecov', require: false
end
Then install the gems:
bash
bundle install
3. Initialize RSpec and Configuration
Run the generator to install RSpec.
bash
rails generate rspec:install
Now, edit spec/rails_helper.rb to configure DatabaseCleaner, FactoryBot, and Shoulda-Matchers.
spec/rails_helper.rb
ruby
# require simplecov at the very top
require 'simplecov'
SimpleCov.start 'rails' do
add_filter '/bin/'
add_filter '/db/'
add_filter '/spec/' # exclude test code from coverage metrics
end
# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
require 'database_cleaner/active_record'
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories.
Rails.root.glob('spec/support/**/*.rb').sort.each { |f| require f }
RSpec.configure do |config|
# Use FactoryBot methods without writing `FactoryBot.` prefix
config.include FactoryBot::Syntax::Methods
# Start with a clean database
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.around(:each) do |example|
DatabaseCleaner.cleaning do
example.run
end
end
# Mix in different types of tests (controller, request, etc.)
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
end
# Configure Shoulda-Matchers
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
4. CORS Configuration (Optional but Recommended)
If your frontend is on a different domain/port, you need CORS.
Uncomment gem 'rack-cors' in your Gemfile and bundle install.
Create an initializer config/initializers/cors.rb:
ruby
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*' # In production, replace with your specific frontend domain
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
5. Example: Model and Request Specs
Let's create a scaffold to see the boilerplate in action.
bash
rails g scaffold Article title:string body:text
rails db:migrate
The Model Spec (spec/models/article_spec.rb)Tests validations and logic.
ruby
require 'rails_helper'
RSpec.describe Article, type: :model do
# Using Shoulda-Matchers for concise one-liners
it { is_expected.to validate_presence_of(:title) }
it { is_expected.to validate_presence_of(:body) }
# Example custom method test
describe '#summary' do
it 'returns the first 10 characters of the body' do
article = create(:article, body: "This is a very long body text")
expect(article.summary).to eq("This is a ")
end
end
end
The Request Spec (spec/requests/articles_spec.rb)Tests the JSON API endpoints.
ruby
require 'rails_helper'
RSpec.describe "Articles", type: :request do
let!(:article) { create(:article) }
let(:valid_attributes) { attributes_for(:article) }
describe "GET /articles" do
before { get '/articles' }
it 'returns status code 200' do
expect(response).to have_http_status(:ok)
end
it 'returns the articles list' do
json_response = JSON.parse(response.body)
expect(json_response).not_to be_empty
# Adjust expectation based on your actual JSON structure
expect(json_response.first['title']).to eq(article.title)
end
end
describe "POST /articles" do
context 'with valid params' do
before { post '/articles', params: { article: valid_attributes } }
it 'returns status code 201' do
expect(response).to have_http_status(:created)
end
it 'creates an article' do
expect(Article.count).to eq(2) # 1 created by let! + 1 created here
end
end
end
end
6. JSON Serialization (Best Practice)
Rails default render json: object works, but for complex APIs, use a serializer. A modern choice is blueprinter or active_model_serializers.
Add to Gemfile:
ruby
gem 'blueprinter'
Create a blueprint:
app/blueprints/article_blueprint.rb
ruby
class ArticleBlueprint < Blueprinter::Base
identifier :id
fields :title, :body
end
Render in controller:
ruby
render json: ArticleBlueprint.render(@articles)
7. Running the Tests
To run your suite:
bash
bundle exec rspec
# or simply
bundle exec rspec spec/
Summary of Files Created/Modified
Gemfile: Added rspec-rails, factory_bot, faker, shoulda-matchers, etc.
spec/rails_helper.rb: Configured DatabaseCleaner and FactoryBot syntax methods.
config/initializers/cors.rb: Enabled CORS for API access.