【山竹记账后端】14.migration、自定义校验、ISO8601 等
大纲链接 §
[toc]
使用测试驱动实现
post /api/v1/items
创建model,运行db:migrate创建controller- 写测试
- 写代码
- 写文档(测试代码)
1. 测试创建item接口 ⇧
完善创建账目测试用例 ⇧
spec/requests/api/v1/items_spec.rb
|
|
- 运行
rspec spec/requests/api/v1/items_spec.rb:100 测试用例失败,打印信息:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26rspec spec/requests/api/v1/items_spec.rb:100 ✘ 1 no Run options: include {:locations=>{"./spec/requests/api/v1/items_spec.rb"=>[100]}} "_______________________" "json" {"resource"=>{"id"=>427, "user_id"=>nil, "amount"=>99, "note"=>nil, "tags_id"=>nil, "happened_at"=>nil, "created_at"=>"2026-11-30T09:43:02.066Z", "updated_at"=>"2026-11-30T09:43:02.066Z"}} "_______________________" F Failures: 1) Api::V1::Items 创建账目 登录后创建 Failure/Error: expect(json['resource']['user_id']).to eq user.id expected: 348 got: nil (compared using ==) # ./spec/requests/api/v1/items_spec.rb:115:in `block (3 levels) in <top (required)>' Finished in 0.04244 seconds (files took 0.68256 seconds to load) 1 example, 1 failure Failed examples: rspec ./spec/requests/api/v1/items_spec.rb:100 # Api::V1::Items 创建账目 登录后创建"resource"=>{"id"=>427, "user_id"=>nil, ...用户id 为空,数据库中无此字段,需要在
controller添加
修复创建账目功能 ⇧
app/controllers/api/v1/items_controller.rb
|
|
- 再次运行
rspec spec/requests/api/v1/items_spec.rb:100,通过测试用例 - 从
params中获取多个字段,可使用简单的写法:item = Item.new params.permit(:amount, :tags_id, :happened_at)
- 直接运行测试用例报错
controller可重构为:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23class Api::V1::ItemsController < ApplicationController # 分页查询账目. # @return [Object] def index # ... end # 创建账目. # @return [Object] def create p("create_______________________") p "params" p params p("_______________________create") item = Item.new params.permit(:amount, :happened_at, :note, tags_id: []) item.user_id = request.env["current_user_id"] if item.save render json: { resource: item } else render json: { errors: item.errors }, status: :unprocessable_entity end end end注意原来写
item = Item.new params.permit(:amount, :tags_id, :happened_at)会报错:tags_id以Symbol形式传给permit- 其中
:tags_id是一个数组,需要改为使用tags_id: [],并且写在参数最后位置 - 必须显式地告诉
rubyparams中:tags_id是一个数组,否则permit不会智能转换
json["resource"]["tags_id"]为nil之前报错的原因为在控制器的强参数许可:params.permit(:amount, :tags_id, :happened_at, :note)把:tags_id当作标量键处理- 而强参数的
PERMITTED_SCALAR_TYPES不包含Array,所以数字数组值[1065]被静默丢弃 - 其他字段均为标量,不受影响,因此只有
tags_id断言失败 Array不在列表中,因此tags_id: [1065]被整键丢弃,Item.new收不到该键,tags_id默认为nil- 最终导致
Item#tags_id为nil
正确写法是把数组参数用哈希形式许可,并因
Ruby语法/强参数过滤顺序要求放在最后:params.permit(:amount, :happened_at, :note, tags_id: [])
再次运行
rspec spec/requests/api/v1/items_spec.rb:100,通过测试用例
tags_id: []的含义
- 在
Strong Parameters中,key: []表示“许可该键,且其值必须是标量数组”hash_filter分支filter[key] == EMPTY_ARRAY- 走
array_of_permitted_scalars?,逐元素检查是否为permitted scalar
- 与
:tags_id(标量)不同,tags_id: []不要求值本身是标量 - 而是要求值是“标量元素组成的数组”,因此
[1065](Integer 元素)会被保留,而[{"x"=>1}]这类非标量数组仍被过滤。
为什么
tags_id: []必须放在最后
- Ruby
语法约束:permit的签名是permit(*filters),裸哈希只能作为最后一个位置参数。
- 写成
params.permit(:amount, tags_id: [], :happened_at, :note)会在解析阶段就报 SyntaxError: unexpected ':', expecting ')'(或类似 syntax error, unexpected ...- 控制器甚至无法加载。因此所有哈希形式的数组/嵌套参数都必须排在标量
Symbol之后。
- 过滤器顺序语义:
permit按filters.flatten的顺序依次执行permitted_scalar_filter / hash_filter;
- 把数组声明放在最后可避免前面的标量过滤误吞掉同名键的数组值,也与
Rails文档推荐的“标量在前、复合/数组在后”一致。
- 常见报错场景:
- 中间插入
tags_id: [] → Ruby语法错误,启动/加载失败。 - 仍写
:tags_id→ 无语法错误但运行时静默丢弃数组,响应tags_id为nil(本次报错)。 - 写成
tags_id: {}→ 被当作空Hash许可,数组值被丢弃。 - 元素为非标量(如对象数组)→
array_of_permitted_scalars?不yield,结果仍为nil。
添加创建账目api文档 ⇧
spec/acceptance/items_spec.rb
|
|
2. 给数据库添加字段,迁移数据库 ⇧
给 item 表添加字段,准备迁移数据库 ⇧
目前没有考虑
Item中那些字段是必填的,所以,这里添加字段,并迁移数据库
- 目前
app/models/item.rb中没有做任何的限制
查看
db/schema.rb,哪些字段是必填的
|
|
- 可以在
ruby层面做限制 create_table "items"其中amount、tags_id、happened_at是必填的create_table "items"还少了一个字段kind,来区分账目是支出还是收入需要数据库迁移添加字段
bin/rails g migration add_kind_to_item或者运行
bin/rails g migration AddKindToItem生成的文件名称自动会变为snake_case1 2 3bin/rails g migration AddKindToItem invoke active_record create db/migrate/20261130131843_add_kind_to_item.rb
实现添加
item表的kind栏db/migrate/20261130131843_add_kind_to_item.rb
|
|
:items表示给items表添加字段:kind表示添加列字段名称为kind:integer表示字段类型为integer:default: 1表示默认值为1,具体代表什么是由开发者定的null: false表示字段不能为空- 之后运行
bin/rails db:migrate
迁移数据库,给 app/models/item.rb 添加枚举,具体写明支持、收入类型 ⇧
运行
bin/rails db:migrate
|
|
查看
db/schema.rb
|
|
- 此时已自动添加
t.integer "kind", default: 1, null: false
app/models/item.rb
|
|
修复并添加字段缺省的测试用例代码 ⇧
spec/requests/api/v1/items_spec.rb
|
|
- 登录后创建时必填 amount 的测试用例
- 不传
amount: params: { tags_id: [tag.id], happened_at: Time.now, kind: 'expense' }
- 不传
expect(response).to have_http_status :unprocessable_content返回状态码 422expect(json['errors']['amount'][0]).to eq "can't be blank"表示必填运行测试
rspec rspec spec/requests/api/v1/items_spec.rb:1161 2 3 4 5 6 7 8 9 10 11 12 13 14Failures: 1) Api::V1::Items 创建账目 登录后创建时必填 amount Failure/Error: expect(response).to have_http_status :unprocessable_content expected the response to have status code :unprocessable_content (422) but it was :ok (200) # ./spec/requests/api/v1/items_spec.rb:122:in `block (3 levels) in <top (required)>' Finished in 0.14239 seconds (files took 0.6289 seconds to load) 9 examples, 1 failure Failed examples: rspec ./spec/requests/api/v1/items_spec.rb:116 # Api::V1::Items 创建账目 登录后创建时必填 amount报了错就可以修改
app/models/item.rb代码了model 中没有添加校验逻辑
app/models/item.rb
|
|
- 再次运行测试
rspec rspec spec/requests/api/v1/items_spec.rb:116通过
添加更多字段缺省的测试用例 ⇧
app/models/item.rb
|
|
spec/requests/api/v1/items_spec.rb
|
|
再次运行测试
rspec rspec spec/requests/api/v1/items_spec.rb:116报错1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27rspec spec/requests/api/v1/items_spec.rb:116 Run options: include {:locations=>{"./spec/requests/api/v1/items_spec.rb"=>[116]}} "登录后创建时必填_______________________" "json" {"errors"=>{"amount"=>["can't be blank"], "tags_id"=>["can't be blank"], "happened_at"=>["can't be blank"]}} "_______________________登录后创建时必填" F Failures: 1) Api::V1::Items 创建账目 登录后创建时必填 amount、kind、tags_id、happened_at Failure/Error: expect(json['errors']['kind'][0]).to eq "can't be blank" NoMethodError: undefined method `[]' for nil:NilClass expect(json['errors']['kind'][0]).to eq "can't be blank" ^^^ # ./spec/requests/api/v1/items_spec.rb:128:in `block (3 levels) in <top (required)>' Finished in 0.03872 seconds (files took 0.68121 seconds to load) 1 example, 1 failure Failed examples: rspec ./spec/requests/api/v1/items_spec.rb:116 # Api::V1::Items 创建账目 登录后创建时必填 amount、kind、tags_id、happened_at此处没有
kind的报错,猜测数据库默认值就有
app/controllers/api/v1/items_controller.rb中打印出item
|
|
|
|
- 发现默认值有
expenses,是在数据库中默认指定的t.integer "kind", default: 1, null: false - 所以没有必要再校验
kind字段,修改相关测试用例,去除kind相关校验代码 - 再次运行测试
rspec rspec spec/requests/api/v1/items_spec.rb:116成功
修复之前的测试用例,添加必填字段 ⇧
- 再次运行测试
rspec rspec spec/requests/api/v1/items_spec.rb发现之前的测试用例报错
spec/requests/api/v1/items_spec.rb
|
|
- 再次运行测试
rspec rspec spec/requests/api/v1/items_spec.rb通过
3. ISO8601 时间字符串 ⇧
spec/requests/api/v1/items_spec.rb
|
|
- 测试
happened_at字段,确认happened_at的类型为ISO8601时间字符串 - 尝试使用不同字符串:
2027-01-01、2027-01-01T00:00:00+08:00测试用例 - 断言
expect(json['resource']['happened_at']).to eq "2027-01-01T00:00:00.000Z" - 运行
rspec spec/requests/api/v1/items_spec.rb:121通过 - 说明传参
happened_at: "2027-01-01"传的就是标准时间 - 存在数据库的到底是什么日期:北京时间的
2027-01-01如何表示happened_at: "2027-01-01T00:00:00+08:00"- 前端必须按照以上的格式给后端传参
happened_at
- 再次断言
expect(json['resource']['happened_at']).to eq "2027-01-01T00:00:00+08:00" 运行
rspec spec/requests/api/v1/items_spec.rb:121失败1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21rspec spec/requests/api/v1/items_spec.rb:121 no Run options: include {:locations=>{"./spec/requests/api/v1/items_spec.rb"=>[121]}} F Failures: 1) Api::V1::Items 创建账目 登录后创建 Failure/Error: expect(json['resource']['happened_at']).to eq "2027-01-01T00:00:00+08:00" expected: "2027-01-01T00:00:00+08:00" got: "2026-12-31T16:00:00.000Z" (compared using ==) # ./spec/requests/api/v1/items_spec.rb:134:in `block (3 levels) in <top (required)>' Finished in 0.04959 seconds (files took 0.67733 seconds to load) 1 example, 1 failure Failed examples: rspec ./spec/requests/api/v1/items_spec.rb:121 # Api::V1::Items 创建账目 登录后创建实际上获取的时间是
2026-12-31T16:00:00.000Z,虽然这个时间和2027-01-01T00:00:00+08:00在绝对意义上是相等的只不过时区不同,所以时间字符串不相等;时区可转
将断言改为
expect(json['resource']['happened_at']).to eq "2026-12-31T16:00:00.000Z"这个标准格式称为
ISO8601,所有工业标准的时间表示方法都是ISO8601,不要使用时间戳或者其他字符串表示时间
参考
- ISO 8601 wiki
- ISO 8601 Date and time format
- ISO 8601
- A summary of the international standard date and time notation
4. 自定义校验 ⇧
model 层添加自定义校验 ⇧
目前后端没有对
tags_id做校验,前端可绕过随便传任意的值,比如1, 2, 3
- 在存储
tag数据前添加校验逻辑- 需要添加对
tags_id是否存在的校验 - 需要添加对
tags_id的用户所属是否一致的校验,防止遍历标签获取任意用户的标签
- 需要添加对
需要在 model 层添加校验逻辑
app/models/item.rb
|
|
validate :check_tags_id_belong_to_user- 单数形式的
validate是自定义校验 - 复数形式的
validates是内置的标准校验,只需要完方法名,方法名就是校验的名称
- 单数形式的
- 获取当前用户的所有 id 列表:
Tag.where(user_id: self.user_id).map(&:id)self指当前账目Item对象.map(&:id)等价于.map(|tag| tag.id )的简写,只是获取某个对象的属性值,&表示当前对象
- 发现后端定义的
tags_id字段错误,需要修改字段名称为tag_ids,目前暂时不该,等之后重构统一处理
ruby 集合判断是否包含演示说明 ⇧
- 判断
self.tags_id & all_tag_ids_of_current_user != self.tags_id - 集合是否包含于
all_tag_ids_of_current_user集合- 求交集运算
&:集合 A 和集合 B 的交集就是 A 本身,那就说明集合 A 包含于集合 B
- 求交集运算
使用控制台
bin/rails c演示1 2 3 4 5 6 7 8 9 10bin/rails c Loading development environment (Rails 7.2.3.2) 3.1.2 :001 > a1 = [1,2,3] => [1, 2, 3] 3.1.2 :002 > a2 = [1,2,3,4,5,6] => [1, 2, 3, 4, 5, 6] 3.1.2 :003 > a1 & a2 => [1, 2, 3] 3.1.2 :004 > a1 & a2 == a1 => trueruby中==运算可以遍历集合/数组,递归对比,判断集合是否相等而
.equal?才是引用判断,判断两个对象是否相等1 2 3 4 5 6bin/rails c Loading development environment (Rails 7.2.3.2) 3.1.2 :005 > [1,2] == [1,2] => true 3.1.2 :006 > [1,2].equal? [1,2] => false
修改测试用例,使得当前测试用例的校验判断通过 ⇧
self.tags_id & all_tag_ids_of_current_user != self.tags_id表示:- 当前账目的标签 id 列表是否属于当前用户的所有标签 id
- 如果不相等,则说明当前用户没有权限访问该标签
- 如果不包含,则添加错误信息
self.errors.add :tags_id, "不属于当前用户"self.errors.add <key> <value>会自动让save操作报错,返回错误信息给前端
现在重新测试
rspec spec/requests/api/v1/items_spec.rb:121查看报错:
|
|
|
|
- 需要创建属于当前用户的
tag标签,再将标签tags_id添加到账目中
app/controllers/api/v1/items_controller.rb
|
|
- 需要添加
item.save!主动抛出错误,并使用rescue ActiveRecord::RecordInvalid进行局部捕获 - 使用
render json: { errors: item.errors }, status: :unprocessable_content进行兜底的错误返回 - 正常成功返回
render json: { resource: item } if item.save!
再修改测试用例
spec/requests/api/v1/items_spec.rb
|
|
- 再运行
rspec spec/requests/api/v1/items_spec.rb:140通过测试
参考
5. 更新API文档,发现之前获取的测试用例由于缺少必传字段校验失败 ⇧
更新文档测试用例 ⇧
spec/acceptance/items_spec.rb
|
|
- 遍历数组生成标签
(0..1).map{|i| Tag.create name: "tag#{i}", sign: '😄', user_id: ... }(0..1)和[0, 1]等价,但写法上更方便通用
- 标签列表
let(:tags_id) { tags.map(&:id) } 运行
bin/rake docs:generate报错,之前获取的测试用例由于缺少必传字段校验失败1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17Failures: 1) 账目 GET /api/v1/items 获取账目 Failure/Error: expect(json["resources"].size).to eq 10 expected: 10 got: 0 (compared using ==) # ./spec/acceptance/items_spec.rb:36:in `block (3 levels) in <top (required)>' Finished in 0.19679 seconds (files took 0.64686 seconds to load) 9 examples, 1 failure Failed examples: rspec ./spec/acceptance/items_spec.rb:29 # 账目 GET /api/v1/items 获取账目在
app/models/item.rb中添加了很多之前没有的校验逻辑,导致测试用例中Item.create失败需要更精确的报错信息,必须添加
Item.create!
修改
spec/acceptance/items_spec.rb,添加Item.create!使报错更精确
|
|
再运行
bin/rake docs:generate查看报错:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20Failures: 1) 账目 GET /api/v1/items 获取账目 Failure/Error: Item.create! amount: 100, created_at: "2026-11-20", user_id: current_user.id ActiveRecord::RecordInvalid: Validation failed: Tags can't be blank, Happened at can't be blank, Tags 不属于当前用户 # ./spec/acceptance/items_spec.rb:28:in `block (4 levels) in <top (required)>' # ./spec/acceptance/items_spec.rb:27:in `times' # ./spec/acceptance/items_spec.rb:27:in `block (3 levels) in <top (required)>' Finished in 0.19117 seconds (files took 0.61841 seconds to load) 9 examples, 1 failure Failed examples: rspec ./spec/acceptance/items_spec.rb:26 # 账目 GET /api/v1/items 获取账目 ...Item.create!就把所有报错的信息返回Validation failed: Tags can't be blank, Happened at can't be blank, Tags 不属于当前用户所以测试尽量使用带带
!的方法,这样报错信息会更准确
修改
spec/acceptance/items_spec.rb
|
|
- 再次运行
bin/rake docs:generate成功生成文档 - 查看生成的文档页面
pnpx http-server doc/api/.
6. 修复账目获取(分页)测试用例 ⇧
在 RequestTestHelper 中提取辅助方法,消除测试中的重复数据构造代码 ⇧
- 重新启用
spec_helper中RequestTestHelper模块的引入
spec/spec_helper.rb
|
|
提取辅助方法
spec/support/rspec_request_test_helper.rb
|
|
gen_2items_of_diff_users用于分页验证获取账目列表gen_common_item_attr用于获取账目列表-按日期筛选
使用辅助方法重构测试用例 ⇧
spec/requests/api/v1/items_spec.rb
|
|
- 将测试中硬编码的日期改为基于
Time.now的相对时间,提高可维护性 get '/api/v1/items'参数传递统一使用params:选项替代字符串拼接
7. 可能的报错信息 ⇧
密钥相关报错
- 拿到代码后,可能需要重新创建密钥:
https://docs.qq.com/doc/DU3ByQXZWbFpQRHND。 - 这一步是可选的,但如果遇到
ActiveSupport::MessageEncryptor::InvalidMessage报错,那么你就必须重新创建密钥了。
参考文章
相关文章
- 无
- 作者: Joel
- 文章链接:
- 版权声明
- 非自由转载-非商用-非衍生-保持署名