【山竹记账后端】9.mock、order、enum 等知识点
大纲链接 §
[toc]
如何测试确实有发送验证码?
- 之前是调用
UserMailer.welocme_email(code).deliver这个方法去发送邮件的 - 需要测试验证访问
/api/v1/validation_codes确实调用了发送验证码的方法,就是证明确实发送了验证码 - 单元测试不测第三方服务,比如邮件接口服务,支付接口服务,只测试本单元的功能,即调用发送邮件的方法
1. 如何 mock ⇧
完善 UserMailer 逻辑与测试用例 ⇧
acceptance/validation_codes_spec.rb
|
|
expect(UserMailer).to receive(:welcome_email).with(email)期待UserMailer接收到:welcome_email调用- 然后再发请求
do_request
修改
app/controllers/api/v1/validation_codes_controller.rb
|
|
- 添加调用
UserMailer.welcome_email(validation_code.email)
然后执行测试命令
bin/rake docs:generate
- 先写预期
- 再去写实现代码
在 validation_codes 表中找到刚生成的 code ⇧
修改方法传参为email地址
app/mailers/user_mailer.rb
|
|
更改模板
app/views/user_mailer/welcome_email.html.erb
|
|
2. 使用 rails console 手动测试 email ⇧
控制台构造数据 ⇧
打开控制台
bin/rails c1 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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51bin/rails c no Loading development environment (Rails 7.2.3.2) 3.1.2 :001 > validation_code = ValidationCode.new email: 'xxx@qq.com', kind: 'sign_in', code: '123456' => #<ValidationCode:0x00007005599e34b8 id: nil, email: "[FILTERED]", kind: 0, code: "123456", used_at: nil, created_at: nil, updated_at: nil> # 保存到数据库中 3.1.2 :002 > validation_code.save TRANSACTION (0.2ms) BEGIN ValidationCode Create (3.4ms) INSERT INTO "validation_codes" ("email", "kind", "code", "used_at", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["email", "[FILTERED]"], ["kind", 0], ["code", "123456"], ["used_at", nil], ["created_at", "2026-11-23 08:15:49.331827"], ["updated_at", "2026-11-23 08:15:49.331827"]] TRANSACTION (2.0ms) COMMIT => true 3.1.2 :003 > UserMailer.welcome_email('xxx@qq.com').deliver ValidationCode Load (0.4ms) SELECT "validation_codes".* FROM "validation_codes" WHERE "validation_codes"."email" = $1 LIMIT $2 [["email", "[FILTERED]"], ["LIMIT", 1]] Rendering layout layouts/mailer.html.erb Rendering user_mailer/welcome_email.html.erb within layouts/mailer Rendered user_mailer/welcome_email.html.erb within layouts/mailer (Duration: 0.1ms | GC: 0.0ms) Rendered layout layouts/mailer.html.erb (Duration: 0.2ms | GC: 0.0ms) UserMailer#welcome_email: processed outbound mail in 1.7ms Delivered mail 6b03f8e6611ae_1a9f1dc02561b@d689d0c4ea6b.mail (1054.1ms) Date: Mon, 23 Nov 2026 16:27:18 +0800 From: xxx@qq.com To: xxx@qq.com Message-ID: <6b03f8e6611ae_1a9f1dc02561b@d689d0c4ea6b.mail> Subject: =?UTF-8?Q?=E5=B1=B1=E7=AB=B9=E8=AE=B0=E8=B4=A6=E9=AA=8C=E8=AF=81=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable <!-- BEGIN app/views/layouts/mailer.html.erb --><!DOCTYPE html> <html lang=3D"zh-CN"> <head> <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3Dutf= -8"> <style> /* Email styles need to be inline */ </style> <title>=E5=B1=B1=E7=AB=B9=E8=AE=B0=E8=B4=A6=E9=82=AE=E7=AE=B1=E9=AA=8C= =E8=AF=81=E7=A0=81</title> </head> <body> <!-- BEGIN app/views/user_mailer/welcome_email.html.erb --><p> =E6=82=A8=E6=AD=A3=E5=9C=A8=E7=99=BB=E5=BD=95=E5=B1=B1=E7=AB=B9=E8=AE=B0= =E8=B4=A6App=EF=BC=8C=E9=AA=8C=E8=AF=81=E7=A0=81=E6=98=AF: <code>#<Val= idationCode:0x00007f5c4b4f5a98></code> </p><!-- END app/views/user_mailer/welcome_email.html.erb --> </body> </html> <!-- END app/views/layouts/mailer.html.erb -->= => #<Mail::Message:12680, Multipart: false, Headers: <Date: Mon, 23 Nov 2026 16:27:18 +0800>, <From: xxx@qq.com>, <To: xxx@qq.com>, <Message-ID: <6b03f8e6611ae_1a9f1dc02561b@d689d0c4ea6b.mail>>, <Subject: 山竹记账验证码>, <MIME-Version: 1.0>, <Content-Type: text/html>, <Content-Transfer-Encoding: quoted-printable>>创建实例对象
validation_code = ValidationCode.new email: 'xxx@qq.com', kind: 'sign_in', code: '123456'保存到数据库中
validation_code.save手动发送
UserMailer.welcome_email('xxx@qq.com').deliver查看收件邮箱是否已发送成功
用户有可能提交了很多个
validation_code,需要找到最新的validation_code
3. 重构:使用钩子 ⇧
重构生成验证码逻辑 ⇧
validation_codes_controller.rb超过五行
- 实例化
ValidationCode.new email: params[:email], kind: "sign_in", code: code- 其中生成
code的逻辑考虑放到数据层中app/models/validation_code.rb - 每次实例化自动调用钩子函数,创建一个随机码
- 其中生成
在
app/models/validation_code.rb中使用钩子函数
|
|
after_initialize :generate_code构成名称为after_initialize构造函数- 被构造后就会去执行
generate_code方法 - 对象实例
ValidationCode.new执行之后调用generate_code,就自动会有code
验证是否生成了
code修改app/controllers/api/v1/validation_codes_controller.rb
|
|
运行
bin/rake docs:generate1 2 3 4 5 6 7 8 9 10 11 12 13Generating API Docs Items GET /api/v1/items * Listing items 验证码api POST /api/v1/validation_codes "validation_code_______________________" #<ValidationCode id: nil, email: [FILTERED], kind: 0, code: "282587", used_at: nil, created_at: nil, updated_at: nil> "_______________________validation_code" * 请求发送验证码 Finished in 0.09059 seconds (files took 0.52279 seconds to load) 2 examples, 0 failures
问题:
kind: 0暂时先留一个伏笔
重构发送邮件逻辑 ⇧
validation_codes_controller.rb发送邮件的逻辑,只要新创建了一个validation_code就会发送邮件
app/models/validation_code.rb将数据操作逻辑写到Model中
|
|
ApplicationRecord即为Model层validation_code.save后执行send_email
app/controllers/api/v1/validation_codes_controller.rb
|
|
Rails 重构优化特点 ⇧
- 尽量把
Controller写短一点 - 如果有和数据相关的操作,全都写到相关的
Model中
4. 如何对记录进行排序 ⇧
user_mailer.rb中validation_code = ValidationCode.find_by_email(email)这样查找
- 比如同一个用户登录了10次,就创建了10个
validation_code,其中的email都是这个用户的 - 需要找到最新的一个,代码中的逻辑就是需要在
find_by_email前对ValidationCode做一个排序
app/mailers/user_mailer.rb
|
|
- `.order(created_at: :desc) 创建时间降序排列
find_by_email只会找第一个- 找到最新的邮箱对应的验证码发送
- 由于依赖了第三方服务,这个功能也是不好测试的
为什么要把 after_initialize 改为 before_create ⇧
- 因为
after_initialize会在每次初始化对象后执行 - 而
before_create只在创建数据库项目时执行,后者才是我们需要的
app/models/validation_code.rb
|
|
5. 如何使用枚举处理kind为0 ⇧
使用控制台复现问题
bin/rails ckind是预留字段,用来区别验证码类型的,不仅登录,后续可扩展,重置密码等其他操作- 控制台输入
v1 = ValidationCode.create email: "1@qq.com", kind: "sign_in" 之后控制台显示以下信息
1 2 3 4 5 6Loading development environment (Rails 7.2.3.2) 3.1.2 :001 > v1 = ValidationCode.create email: "1@qq.com", kind: "sign_in" TRANSACTION (0.2ms) BEGIN ValidationCode Create (3.2ms) INSERT INTO "validation_codes" ("email", "kind", "code", "used_at", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["email", "[FILTERED]"], ["kind", 0], ["code", "353542"], ["used_at", nil], ["created_at", "2026-11-23 09:46:42.547187"], ["updated_at", "2026-11-23 09:46:42.547187"]] TRANSACTION (2.2ms) COMMIT => #<ValidationCode:0x000074c89e0e9be8 id: 4, email: "[FILTERED]", kind: 0, code: "353542", used_at: nil, created_at: "2026-11-23 09:46:42.547187000 +0000", updated_at: "2026-11-23 09:46:42.547187000 +0000">控制台信息中
kind: 0是否与创建数据库时,将kind类型声明为integer
db/schema.rb
|
|
- 使用
enum枚举映射enum kind: { sign_in: 0, reset_password: 1 } - 新写法(位置参数):
enum :kind, { sign_in: 0, reset_password: 1 } - 任何时候使用
kind.sign_in会自动映射为0 - 代码改了需要重新加载一下控制台
reload!,或者ctrl + D退出,重新进入控制台
app/models/validation_code.rb
|
|
再次输入
v1 = ValidationCode.create email: "1@qq.com", kind: "sign_in"1 2 3 4 5 6 7 8 9 10 11 12 13 143.1.2 :004 > v1 = ValidationCode.create email: "1@qq.com", kind: "sign_in" TRANSACTION (0.2ms) BEGIN ValidationCode Create (0.7ms) INSERT INTO "validation_codes" ("email", "kind", "code", "used_at", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["email", "[FILTERED]"], ["kind", 0], ["code", "042113"], ["used_at", nil], ["created_at", "2026-11-23 13:01:46.939877"], ["updated_at", "2026-11-23 13:01:46.939877"]] TRANSACTION (3.3ms) COMMIT 3.1.2 :005 > v1 => #<ValidationCode:0x000078f3c87f0640 id: 6, email: "[FILTERED]", kind: "sign_in", code: "042113", used_at: nil, created_at: "2026-11-23 13:01:46.939877000 +0000", updated_at: "2026-11-23 13:01:46.939877000 +0000">此时查看
v1的内容为sign_in- 在
rails中永远就是sign_in在数据库中永远就是0 - 就不用再去看数据库了,可以把它当作字符串
- 在
现在给前端传的
json里的kind也是字符串;前端传给后端的kind也是字符串Rails做到了数据库不管是数字也好,字符串也好,写代码时不管是前端后端都可以用字符串,既满足了效率,又满足了方便查看数据库:
手动清空之前
ValidationCode数据,控制台中运行ValidationCode.destroy_all1 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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43bin/rails c no Loading development environment (Rails 7.2.3.2) 3.1.2 :001 > ValidationCode.destroy_all ValidationCode Load (22.5ms) SELECT "validation_codes".* FROM "validation_codes" TRANSACTION (0.2ms) BEGIN ValidationCode Destroy (0.6ms) DELETE FROM "validation_codes" WHERE "validation_codes"."id" = $1 [["id", 1]] TRANSACTION (4.3ms) COMMIT TRANSACTION (0.1ms) BEGIN ValidationCode Destroy (0.5ms) DELETE FROM "validation_codes" WHERE "validation_codes"."id" = $1 [["id", 2]] TRANSACTION (1.3ms) COMMIT TRANSACTION (0.1ms) BEGIN ValidationCode Destroy (0.5ms) DELETE FROM "validation_codes" WHERE "validation_codes"."id" = $1 [["id", 3]] TRANSACTION (3.2ms) COMMIT TRANSACTION (0.2ms) BEGIN ValidationCode Destroy (0.6ms) DELETE FROM "validation_codes" WHERE "validation_codes"."id" = $1 [["id", 4]] TRANSACTION (2.5ms) COMMIT TRANSACTION (0.1ms) BEGIN ValidationCode Destroy (0.5ms) DELETE FROM "validation_codes" WHERE "validation_codes"."id" = $1 [["id", 5]] TRANSACTION (5.0ms) COMMIT TRANSACTION (0.1ms) BEGIN ValidationCode Destroy (0.5ms) DELETE FROM "validation_codes" WHERE "validation_codes"."id" = $1 [["id", 6]] TRANSACTION (3.0ms) COMMIT => [#<ValidationCode:0x00007a8343a6b828 id: 1, email: "[FILTERED]", kind: "sign_in", code: "123456", used_at: nil, created_at: "2026-11-23 08:15:49.331827000 +0000", updated_at: "2026-11-23 08:15:49.331827000 +0000">, #<ValidationCode:0x00007a8343a368f8 id: 2, email: "[FILTERED]", kind: "sign_in", code: "123456", used_at: nil, created_at: "2026-11-23 08:23:57.234065000 +0000", updated_at: "2026-11-23 08:23:57.234065000 +0000">, #<ValidationCode:0x00007a8343a36830 id: 3, email: "[FILTERED]", lines 1-20 ...ValidationCode.count统计1 2 33.1.2 :002 > ValidationCode.count ValidationCode Count (0.5ms) SELECT COUNT(*) FROM "validation_codes" => 0
完整的输入控制台查看
|
|
- 控制台可以随时改变,输入
v1.kind = 1 Rails自动帮你匹配,既可以输入数字,又可以输入字符串Rails发现数字,就帮你翻译成字符串,发现使用字符串,就翻译成数字1 2 3 4 5 6 7 83.1.2 :004 > v1.kind = 1 => 1 3.1.2 :005 > v1.kind => "reset_password" 3.1.2 :006 > v1.kind = "sign_in" => "sign_in" 3.1.2 :007 > v1.kind => "sign_in"
参考
6. 如何防止重复发送验证码 ⇧
实现60秒内不能重复发送
- 做后端时的原则,前端不可信,后端必须要做检查,防止各种绕开前端检查的漏洞
思路:每次发送发送验证码之前,看一下刚才有没有发送过验证码
- 如果刚才有发送过验证码,并且时间是在60秒之内,就返回不能发送
app/controllers/api/v1/validation_codes_controller.rb
|
|
- 查找60秒内创建的
ValidationCodeValidationCode.where(email: params[:email], kind: "sign_in", created_at: 1.minutes.ago..Time.now)
或者改用检测是否有
ValidationCode的api
|
|
exists?:Ruby里面有一个特点,如果函数返回值的类型是布尔,那么这个函数的结尾就是个问号- 这个问号是函数名的一部分
参考
使用
Ruby中的if语法糖app/controllers/api/v1/validation_codes_controller.rb
|
|
7. 两种测试:acceptance 和 requests ⇧
实现验证码基本测试 ⇧
如何测试多次请求
- 发了一次请求,再
do_request即可
spec/acceptance/validation_codes_spec.rb
- 先让测试错一次,状态码改为
422 运行
bin/rake docs:generate1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17require 'rails_helper' require 'rspec_api_documentation/dsl' resource "验证码api" do post "/api/v1/validation_codes" do parameter :email, type: :string let(:email) { '1@qq.com' } example "请求发送验证码" do expect(UserMailer).to receive(:welcome_email).with(email) do_request expect(status).to eq 200 expect(response_body).to eq " " do_request expect(status).to eq 422 end end end
测试结果
|
|
再改为
429,运行bin/rake docs:generate1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17require 'rails_helper' require 'rspec_api_documentation/dsl' resource "验证码api" do post "/api/v1/validation_codes" do parameter :email, type: :string let(:email) { '1@qq.com' } example "请求发送验证码" do expect(UserMailer).to receive(:welcome_email).with(email) do_request expect(status).to eq 200 expect(response_body).to eq " " do_request expect(status).to eq 422 end end end
测试结果
|
|
实现验证码其他功能测试 ⇧
目前查看文档,会显示错误的状态码
Status 429 too many request
- 因为最后发的请求处理结果为
429 - 需要区别对待两种不同的测试
- 一种是
acceptance,可接受代码的测试 - 一种是
reuests其他测试
- 一种是
spec/requests/validation_codes_spec.rb
|
|
这次需要使用命令
rspec运行测试,这个测试会运行spec目录中所有的测试用例1 2 3 4....... Finished in 0.09502 seconds (files took 0.90465 seconds to load) 7 examples, 0 failures一个
describe就是一个用例;一个
resource也算一个用例,是属于acceptance的用例用于生成api文档意外情况都写到
request中的测试用例中可以发现这两种测试的语法也不同
8. 可能的报错信息 ⇧
密钥相关报错 ⇧
- 拿到代码后,可能需要重新创建密钥:
https://docs.qq.com/doc/DU3ByQXZWbFpQRHND。 - 这一步是可选的,但如果遇到
ActiveSupport::MessageEncryptor::InvalidMessage报错,那么你就必须重新创建密钥了。
参考文章
相关文章
- 无
- 作者: Joel
- 文章链接:
- 版权声明
- 非自由转载-非商用-非衍生-保持署名