Modifying the Gemfile
I'm working on modifying the Gemfile for a Rails project. In the development and test groups, I want to include rspec-rails, factory_bot_rails, and faker. Although I note that database_cleaner-active_record is optional in Rails 5.1+, I wonder if it's best to keep things minimal and maybe just include rspec-rails and factory_bot_rails. After that, I plan to run bundle install followed by rails generate rspec:install. I'll add specific flags in the .rspec file too!Setting Up the User Model
I'm detailing the setup for a User model in a Rails app. I plan to run some commands to generate the model and the API controller, which will handle typical CRUD actions without helpers or assets. After that, I'll define strong parameters in the users_controller.rb and set up the necessary routes in routes.rb using namespaces.
Next, I’ll incorporate model validations and create example specs to ensure everything works as expected. I ponder whether to use shoulda-matchers for more straightforward tests, but I'm leaning towards keeping it simple with manual tests instead.Writing Validation Tests
I'm setting up validation tests for the User model. I'll show an example where a User is invalid without a name, using RSpec to check that the error message is as expected. There's no need for any additional gems since we're already using factory_bot. I plan to define a minimal factory for users in spec/factories/users.rb.
Next, I'll create a request spec in spec/requests/api/v1/users_spec.rb to test CRUD actions. I'll also remember to include rails_helper and utilize FactoryBot for creating user instances. Finally, I need to make sure everything is written clearly and correctly!Setting Up UsersController
I’m defining the UsersController for the API. It includes several methods for handling user data: index retrieves all users, show gets a specific user, and create attempts to save a new user while returning errors if it fails. The update method changes existing user details, and destroy removes a user.
I need to remember that the ApplicationController for API-only applications inherits from ActionController::API, and the newly created application_controller.rb doesn’t need modifications. I'll ensure everything is clearly organized and accurate!Creating RSpec Request Specs
I’m setting up RSpec for request specs for the Users API. I’ll start by making sure to include rails_helper in the spec files. I want to define a request test to verify that all users are returned correctly from the API.
In request_spec_helper.rb, I need to ensure it requires supportive files, and I’ll add a snippet to rails_helper.rb to include this. I should also cover the .rspec file configuration for clarity. Once we clarify the steps, I’ll structure them appropriately, noting that this setup works for both Rails 6 and 7! Below is a minimal Rails API + RSpec boilerplate you can copy into a new project.
1. Generate a new API-only Rails app
# Rails 6/7
rails new my_api --api -T
cd my_api
--api makes it API-only; -T skips default Test::Unit.
2. Gemfile (RSpec + helpers)
In Gemfile:
group :development, :test do
gem 'rspec-rails'
gem 'factory_bot_rails'
end
Then:
bundle install
rails generate rspec:install
This creates .rspec, spec/spec_helper.rb, and spec/rails_helper.rb.
3. RSpec configuration
.rspec
--require spec_helper
--format documentation
--color
spec/rails_helper.rb (relevant additions)
After running rails generate rspec:install, edit spec/rails_helper.rb and add:
# 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'
# Require support files (helpers, shared contexts, etc.)
Dir[Rails.root.join('spec/support/**/*.rb')].sort.each { |f| require f }
# Maintain test schema
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
abort e.to_s.strip
end
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# Use DB transactions for tests
config.use_transactional_fixtures = true
# FactoryBot shortcuts: `create(:user)` instead of `FactoryBot.create(:user)`
config.include FactoryBot::Syntax::Methods
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
end
spec/support/request_spec_helper.rb
Create a helper for parsing JSON:
# spec/support/request_spec_helper.rb
module RequestSpecHelper
def json
JSON.parse(response.body)
end
end
RSpec.configure do |config|
config.include RequestSpecHelper, type: :request
end
4. Example resource: User
You can replace this with any resource, but User is a concrete example.
Model + migration
rails generate model User name:string email:string
rails db:create db:migrate
app/models/user.rb:
class User < ApplicationRecord
validates :name, presence: true
validates :email, presence: true, uniqueness: true
end
Namespaced API controller
rails generate controller api/v1/users index show create update destroy --no-helper --no-assets --skip-routes
config/routes.rb:
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :users
end
end
end
app/controllers/api/v1/users_controller.rb:
module Api
module V1
class UsersController < ApplicationController
before_action :set_user, only: %i[show update destroy]
def index
users = User.all
render json: users
end
def show
render json: @user
end
def create
user = User.new(user_params)
if user.save
render json: user, status: :created
else
render json: { errors: user.errors.full_messages },
status: :unprocessable_entity
end
end
def update
if @user.update(user_params)
render json: @user
else
render json: { errors: @user.errors.full_messages },
status: :unprocessable_entity
end
end
def destroy
@user.destroy
head :no_content
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:name, :email)
end
end
end
end
app/controllers/application_controller.rb should already be:
class ApplicationController < ActionController::API
end
5. Factories
spec/factories/users.rb:
FactoryBot.define do
factory :user do
name { "Test User" }
email { "user#{SecureRandom.hex(4)}@example.com" }
end
end
6. Model spec example
spec/models/user_spec.rb:
require 'rails_helper'
RSpec.describe User, type: :model do
describe 'validations' do
it 'is valid with name and email' do
user = User.new(name: 'John', email: 'john@example.com')
expect(user).to be_valid
end
it 'is invalid without a name' do
user = User.new(name: nil, email: 'john@example.com')
expect(user).not_to be_valid
expect(user.errors[:name]).to include("can't be blank")
end
it 'is invalid without an email' do
user = User.new(name: 'John', email: nil)
expect(user).not_to be_valid
expect(user.errors[:email]).to include("can't be blank")
end
it 'is invalid with a duplicate email' do
create(:user, email: 'dup@example.com')
user = User.new(name: 'Other', email: 'dup@example.com')
expect(user).not_to be_valid
expect(user.errors[:email]).to include('has already been taken')
end
end
end
7. Request specs (API tests)
spec/requests/api/v1/users_spec.rb:
require 'rails_helper'
RSpec.describe 'Api::V1::Users', type: :request do
let!(:users) { create_list(:user, 3) }
describe 'GET /api/v1/users' do
it 'returns all users' do
get '/api/v1/users'
expect(response).to have_http_status(:ok)
expect(json.size).to eq(3)
end
end
describe 'GET /api/v1/users/:id' do
it 'returns the user' do
user = users.first
get "/api/v1/users/#{user.id}"
expect(response).to have_http_status(:ok)
expect(json['id']).to eq(user.id)
expect(json['email']).to eq(user.email)
end
end
describe 'POST /api/v1/users' do
let(:valid_params) { { user: { name: 'New User', email: 'new@example.com' } } }
let(:invalid_params) { { user: { name: '' } } }
it 'creates a user with valid params' do
expect {
post '/api/v1/users', params: valid_params
}.to change(User, :count).by(1)
expect(response).to have_http_status(:created)
expect(json['email']).to eq('new@example.com')
end
it 'returns errors with invalid params' do
expect {
post '/api/v1/users', params: invalid_params
}.not_to change(User, :count)
expect(response).to have_http_status(:unprocessable_entity)
expect(json['errors']).to be_present
end
end
describe 'PATCH /api/v1/users/:id' do
it 'updates the user' do
user = users.first
patch "/api/v1/users/#{user.id}", params: { user: { name: 'Updated' } }
expect(response).to have_http_status(:ok)
expect(json['name']).to eq('Updated')
expect(user.reload.name).to eq('Updated')
end
end
describe 'DELETE /api/v1/users/:id' do
it 'deletes the user' do
user = users.first
expect {
delete "/api/v1/users/#{user.id}"
}.to change(User, :count).by(-1)
expect(response).to have_http_status(:no_content)
end
end
end
8. Run tests
bundle exec rspec
This setup gives you:
- API-only Rails app
- RSpec configured
- FactoryBot
- JSON helper for request specs
- Example model and fully tested CRUD JSON API
If you want, I can adapt this boilerplate to a specific Rails version or add extras like authentication, serializers, or Swagger docs.