安装 RSpec
- Gemfile 文件
group :development, :test do
gem "debug", platforms: %i[ mri mingw x64_mingw ]
gem 'rspec-rails', '~> 6.0.0' #新增
end
- 终端运行
# Download and install
$ bundle install
# Generate boilerplate configuration files
# (check the comments in each generated file for more information)
$ bin/rails generate rspec:install
create .rspec
create spec
create spec/spec_helper.rb
create spec/rails_helper.rb
# 创建测试 model 文件
$ bin/rails generate rspec:model user
create spec/models/user_spec.rb
- 配置测试数据库
# config/database.yml
test:
<<: *default
database:
username:
password:
host:
- 在测试环境创建数据库
# 测试环境 创建数据库
RAILS_ENV=test bin/rails db:create
# 测试环境 迁移数据库
RAILS_ENV=test bin/rails db:migrate
- 启动测试用例
bundle exec rspec
如何测试请求
创建测试请求文件
$ bin/rails generate rspec:request items
create spec/requests/items_spec.rb
具体测试用例看项目代码
如何使用 SecureRandom
- 创建测试请求文件
$ bin/rails generate rspec:request validation_codes
create spec/requests/validation_codes_spec.rb
- 完善 controller
ActiveRecord::SecureToken::ClassMethods
# app/controllers/api/v1/validation_codes_controller.rb
class Api::V1::ValidationCodesController < ApplicationController
def create
code = SecureRandom.random_number.to_s[2..7]
validation_code = ValidationCode.new email: params[:email], kind: 'sign_in', code: code
if validation_code.save
head 200
else
reder json: {errors: validation_code.errors}
end
end
end
# app/models/validation_code.rb
class ValidationCode < ApplicationRecord
has_secure_token :code, length: 24
end
Ctrl + P
搜索schema.rb
可以查看有数据表哪些字段