The user didn't specify JSON:API details but mentioned "Rails API," so I’ll assume they want that. I’ll focus on Rails 7 and Ruby 3.x, reflecting best practices as of the 2024 cutoff. Since the user just needs boilerplate, I’ll provide concise, self-contained guidance with some ready-to-use skeleton sections.
I’ll plan sections: 1. Creating a Rails API project. 2. Modifying the Gemfile for RSpec and related gems. 3. Installing and setting up RSpec. 4. Example configuration. 5. A sample model/controller/spec pattern. I'll also touch on configuring the test environment. Let's get crafting!Setting Up Rails API with RSpec
First, I’ll create a new Rails API project using the command rails new my_api --api -T --database=postgresql. Next, I’ll add RSpec and other testing gems to the Gemfile, ensuring I group them correctly for development and test environments.
Then, I’ll run bundle install and generate RSpec with rails generate rspec:install.
I'll detail the contents for .rspec and spec/spec_helper.rb, along with necessary modifications in spec/rails_helper.rb for integrating FactoryBot and DatabaseCleaner, including configurations for Shoulda Matchers. Though DatabaseCleaner is often optional with Rails 5+, it's still commonly used.Simplifying Rails API Setup
I realize I can provide less boilerplate by skipping DatabaseCleaner for a more minimal setup, even though advanced users might want it. The user just requested "boilerplate," not an all-inclusive package.
For the Gemfile, I'll include RSpec, FactoryBot, and Faker under development and test groups, plus Shoulda Matchers for tests. In spec/rails_helper.rb, I’ll configure RSpec to include FactoryBot.
I'll also mention the need for typical API middleware like rack-cors, adding it to the Gemfile and the corresponding initializer. I'll provide code blocks for generating a "Post" model and controller, likely in a namespaced API format, since that's often preferred.Creating a Rails API App
I need to mention that what I’m providing is just one of many possible setups, so the user should adjust versions as necessary.
Let’s structure the response:
Generate the API app.
Gemfile setup.
Install RSpec.
Configure RSpec.
Example resource, including model, migration, routes, controller, specs, and factory.
This should fit what the user means by "boilerplate." I’ll add the spec for requests too, specifically spec/requests/api/v1/posts_spec.rb.
For example, the Post model could be:
ruby
# app/models/post.rb
class Post < ApplicationRecord
validates :title, presence: true
validates :body, presence: true
end
I'll also include details for the migration.Rails API Boilerplate
This is a boilerplate setup for a Rails API application. Adjust versions as needed.
Generate API App
bash
rails new my_api --api -T --database=postgresql
Gemfile
ruby
group :development, :test do
gem 'rspec-rails', '> 6.1'
gem 'factory_bot_rails'
gem 'faker'
end
group :test do
gem 'shoulda-matchers'
end
Routes (config/routes.rb)
ruby
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :posts
end
end
end
class Api::V1::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, :published)
end
end
Model (app/models/post.rb)
This setup provides a solid foundation for a Rails API application. Below is a minimal, modern Rails API + RSpec boilerplate you can copy into a fresh project.
source 'https://rubygems.org'
ruby '3.2.2' # or your version
gem 'rails', '~> 7.1' # or your version
gem 'pg'
# API-related (optional but common)
gem 'rack-cors'
group :development, :test do
gem 'rspec-rails', '~> 6.1' # adjust if needed
gem 'factory_bot_rails'
gem 'faker'
end
group :test do
gem 'shoulda-matchers'
end
Install:
bash
bundle install
Enable CORS if you need it (optional):
config/initializers/cors.rb:
ruby
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*' # change to your frontend domain(s)
resource '*',
headers: :any,
methods: %i[get post put patch delete options head]
end
end
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, :published)
end
end
end
end
Note: In an --api app, ApplicationController already inherits from ActionController::API.
5. RSpec: factories and specs
5.1 Factory
spec/factories/posts.rb:
ruby
FactoryBot.define do
factory :post do
title { Faker::Book.title }
body { Faker::Lorem.paragraph }
published { false }
end
end
5.2 Model spec
spec/models/post_spec.rb:
ruby
require 'rails_helper'
RSpec.describe Post, type: :model do
it { should validate_presence_of(:title) }
it { should validate_presence_of(:body) }
end
5.3 Request specs
spec/requests/api/v1/posts_spec.rb:
ruby
require 'rails_helper'
RSpec.describe 'Api::V1::Posts', type: :request do
let!(:posts) { create_list(:post, 3) }
let(:post_id) { posts.first.id }
describe 'GET /api/v1/posts' do
it 'returns all posts' do
get '/api/v1/posts'
expect(response).to have_http_status(:ok)
json = JSON.parse(response.body)
expect(json.size).to eq(3)
end
end
describe 'GET /api/v1/posts/:id' do
it 'returns a post' do
get "/api/v1/posts/#{post_id}"
expect(response).to have_http_status(:ok)
json = JSON.parse(response.body)
expect(json['id']).to eq(post_id)
end
end
describe 'POST /api/v1/posts' do
let(:valid_params) do
{
post: {
title: 'My Post',
body: 'Some content',
published: true
}
}
end
it 'creates a post' do
expect {
post '/api/v1/posts', params: valid_params
}.to change(Post, :count).by(1)
expect(response).to have_http_status(:created)
end
end
describe 'PATCH /api/v1/posts/:id' do
let(:update_params) { { post: { title: 'Updated Title' } } }
it 'updates the post' do
patch "/api/v1/posts/#{post_id}", params: update_params
expect(response).to have_http_status(:ok)
expect(posts.first.reload.title).to eq('Updated Title')
end
end
describe 'DELETE /api/v1/posts/:id' do
it 'deletes the post' do
expect {
delete "/api/v1/posts/#{post_id}"
}.to change(Post, :count).by(-1)
expect(response).to have_http_status(:no_content)
end
end
end
6. Run tests
bash
# ensure db is migrated
bin/rails db:migrate RAILS_ENV=test
# run all specs
bundle exec rspec
You now have:
Rails API-only app
RSpec configured
FactoryBot + Faker + Shoulda Matchers
Example namespaced API resource with model, controller, routes, and request/model specs
If you want, I can extend this boilerplate with authentication (e.g., JWT), serializers, or a service-object pattern.
ruby
class Post < ApplicationRecord
validates :title, presence: true
validates :body, presence: true
end
Migration
bash
rails g migration CreatePosts title:string body:text published:boolean
Factory (spec/factories/posts.rb)
ruby
FactoryBot.define do
factory :post do
title { Faker::Book.title }
body { Faker::Lorem.paragraph }
published { false }
end
end
Model Spec (spec/models/post_spec.rb)
ruby
require 'rails_helper'
RSpec.describe Post, type: :model do
it { should validate_presence_of(:title) }
it { should validate_presence_of(:body) }
end
Request Spec (spec/requests/api/v1/posts_spec.rb)
ruby
require 'rails_helper'
RSpec.describe 'Api::V1::Posts', type: :request do
let!(:posts) { create_list(:post, 3) }
let(:post_id) { posts.first.id }
describe 'GET /api/v1/posts' do
it 'returns all posts' do
get '/api/v1/posts'
expect(response).to have_http_status(:ok)
json = JSON.parse(response.body)
expect(json.size).to eq(3)
end
end
# Other specs...
end