使用Rails进行RESTful JSON API的测试驱动开发
在本文中,我们将探讨如何使用 Rails 构建一个简单的 API-only 应用程序。与传统的 Rails Web 应用相比,API-only 应用更加精简,适合专注于 JSON API 的开发需求。
使用 Rails 构建 API-only 应用的优势
Rails 提供了一组默认配置,帮助开发者快速启动和运行 API-only 应用,而无需做出许多琐碎的决定。通过使用 --api 标志创建项目,Rails 会进行以下优化:
- 启用一组精简的中间件。
- 让
ApplicationController继承自ActionController::API,而非ActionController::Base。 - 跳过视图文件的生成。
在本教程中,我们将构建一个书店 API,用户可以通过该 API 管理他们最喜欢的书籍列表。
API 端点设计
我们的 API 将公开以下 RESTful 端点:

实体关系图
以下是项目的实体关系图:

项目初始化
通过以下命令快速生成一个新的 Rails 项目:
rails new books-api --api -T -d postgresql
说明:
--api:指定创建 API-only 应用。-d:指定数据库类型为 PostgreSQL。-T:跳过默认测试框架(Minitest),我们将使用 RSpec 进行测试。
添加依赖宝石
在 Gemfile 中添加以下宝石以支持开发和测试:
- rspec-rails:用于 Rails 的测试框架。
- factory_bot_rails:集成 FactoryBot 和 Rails。
- shoulda-matchers:提供简洁的 RSpec 语法,用于测试常见的 Rails 功能。
- database_cleaner:用于清理测试数据库。
- faker:生成虚拟数据,如姓名、地址等。
将这些宝石添加到 :development 和 :test 组中:
group :development, :test do
gem 'rspec-rails'
gem 'factory_bot_rails'
gem 'shoulda-matchers'
gem 'database_cleaner'
gem 'faker'
end
运行以下命令安装宝石:
bundle install
配置 RSpec
安装完成后,初始化 RSpec:
rails generate rspec:install
此命令会生成以下文件:
.rspecspec/spec_helper.rbspec/rails_helper.rb
接下来,创建一个 factories 目录,用于存放 FactoryBot 的工厂文件:
mkdir spec/factories
模型生成与测试驱动开发
生成模型
我们将从生成 Category 和 Book 模型开始:
rails generate model Category name:string
rails generate model Book title:string author:string category:references
运行迁移以创建数据库表:
rails db:create
rails db:migrate
编写模型测试
在 spec/models 目录下,为 Category 和 Book 模型编写测试。借助 Shoulda Matchers,可以轻松测试模型的关联和验证。例如:
# spec/models/category_spec.rb
require 'rails_helper'
RSpec.describe Category, type: :model do
it { should validate_presence_of(:name) }
it { should have_many(:books) }
end
运行测试:
rspec
定义控制器与路由
定义路由
在 config/routes.rb 中定义 API 路由,并使用命名空间进行版本控制:
namespace :api do
namespace :v1 do
resources :categories
resources :books
end
end
生成控制器
为 Category 和 Book 生成控制器:
rails generate controller api/v1/categories
rails generate controller api/v1/books
在控制器中实现基本的 CRUD 操作,并确保返回 JSON 格式的响应。
测试控制器
为每个控制器编写请求测试。例如,在 spec/requests/categories_request_spec.rb 中:
require 'rails_helper'
RSpec.describe 'Categories API', type: :request do
describe 'GET /api/v1/categories' do
it 'returns all categories' do
create_list(:category, 5)
get '/api/v1/categories' expect(response).to have_http_status(:success)
expect(json.size).to eq(5)
end
end
end
运行测试以验证 API 的功能:
rspec
手动测试 API
除了编写自动化测试,还可以使用工具手动测试 API。推荐使用 Postman,它不仅支持测试,还能轻松生成 API 文档。
总结
通过本文的学习,你应该掌握了以下内容:
- 使用 Rails 构建 API-only 应用。
- 配置 RSpec 测试框架,并使用 FactoryBot、Database Cleaner 等工具。
- 使用测试驱动开发(TDD)方法构建模型和控制器。
- 实现 API 的版本控制。
在下一篇文章中,我们将探讨如何使用 JWT 实现 RESTful API 的身份验证。祝你编码愉快!
原文链接: https://www.microverse.org/blog/test-driven-development-of-restful-json-api-with-rails
最新文章
- 使用Spring框架轻松构建REST API | Analytics Vidhya
- 2026大学生寒假兼职新风口:从送外卖到做AI副业,你还在靠体力赚零花钱吗?
- 如何获取Microsoft API Key 密钥实现bing搜索分步指南
- Google Pay UPI 注册与集成指南
- 香港支付宝可以绑定大陆银行卡吗?详解使用方法与步骤
- New API架构:探索现代软件开发的新趋势
- 什么是 Wandb
- 在 Golang 中实现 JWT 令牌认证
- 如何使用 Google News API 获取实时新闻数据
- 理解API网关在微服务架构中的作用
- 交叉熵的Numpy实现:从理论到实践
- Google DeepMind发布 Genie 3与Shopify:2小时上线电商3D样板间实战