【山竹记账后端】9.mock、order、enum 等知识点


大纲链接 §

[toc]


如何测试确实有发送验证码?

  • 之前是调用 UserMailer.welocme_email(code).deliver 这个方法去发送邮件的
  • 需要测试验证访问 /api/v1/validation_codes 确实调用了发送验证码的方法,就是证明确实发送了验证码
  • 单元测试不测第三方服务,比如邮件接口服务,支付接口服务,只测试本单元的功能,即调用发送邮件的方法

1. 如何 mock ⇧

完善 UserMailer 逻辑与测试用例 ⇧

acceptance/validation_codes_spec.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
require 'rails_helper'
require 'rspec_api_documentation/dsl'

resource "验证码api" do
  post "/api/v1/validation_codes" do
    parameter :email, type: :string
    let(:email) { 'xxx@qq.com' }
    example "请求发送验证码" do
      expect(UserMailer).to receive(:welcome_email).with(email)
      do_request
      expect(status).to eq 200
      expect(response_body).to eq " "
    end
  end
end
  • expect(UserMailer).to receive(:welcome_email).with(email) 期待UserMailer接收到:welcome_email调用
  • 然后再发请求 do_request

修改 app/controllers/api/v1/validation_codes_controller.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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
      UserMailer.welcome_email(validation_code.email)
      render status: 200
    else
      render json: { errors: validation_code.errors }, status: 422
    end
  end
end
  • 添加调用 UserMailer.welcome_email(validation_code.email)

然后执行测试命令 bin/rake docs:generate

  • 先写预期
  • 再去写实现代码

在 validation_codes 表中找到刚生成的 code ⇧

修改方法传参为email地址 app/mailers/user_mailer.rb

1
2
3
4
5
6
7
class UserMailer < ApplicationMailer
  def welcome_email(email)
    validation_code = ValidationCode.find_by_email(email)
    @code = validation_code.code
    mail(to: email, subject: "山竹记账验证码")
  end
end

更改模板 app/views/user_mailer/welcome_email.html.erb

1
2
3
<p>
  您正在登录山竹记账App,验证码是: <code><%= @code %></code>
</p>

2. 使用 rails console 手动测试 email ⇧

控制台构造数据 ⇧

  • 打开控制台 bin/rails c

     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
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    
    bin/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>#&lt;Val=
    idationCode:0x00007f5c4b4f5a98&gt;</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 中使用钩子函数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class ValidationCode < ApplicationRecord
  # email必填
  validates :email, presence: true
  # 钩子函数
  after_initialize :generate_code

  def generate_code
    self.code = SecureRandom.random_number.to_s[2..7]
  end
end
  • after_initialize :generate_code 构成名称为 after_initialize 构造函数
  • 被构造后就会去执行generate_code方法
  • 对象实例 ValidationCode.new 执行之后调用 generate_code,就自动会有 code

验证是否生成了code 修改 app/controllers/api/v1/validation_codes_controller.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Api::V1::ValidationCodesController < ApplicationController
  def create
    validation_code = ValidationCode.new email: params[:email], kind: "sign_in"
    p("validation_code_______________________")
    p(validation_code)
    p("_______________________validation_code")
    if validation_code.save
      UserMailer.welcome_email(validation_code.email)
      render status: 200
    else
      render json: { errors: validation_code.errors }, status: 422
    end
  end
end
  • 运行 bin/rake docs:generate

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    
    Generating 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 中

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class ValidationCode < ApplicationRecord
  # email必填
  validates :email, presence: true
  # 钩子函数
  after_initialize :generate_code
  # 保存成功后执行
  after_create :send_email

  def generate_code
    self.code = SecureRandom.random_number.to_s[2..7]
  end

  def send_email
    UserMailer.welcome_email(self.email)
  end
end
  • ApplicationRecord 即为 Model 层
  • validation_code.save 后执行 send_email

app/controllers/api/v1/validation_codes_controller.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Api::V1::ValidationCodesController < ApplicationController
  def create
    validation_code = ValidationCode.new email: params[:email], kind: "sign_in"
    if validation_code.save
      render status: 200
    else
      render json: { errors: validation_code.errors }, status: 422
    end
  end
end

Rails 重构优化特点 ⇧

  • 尽量把 Controller 写短一点
  • 如果有和数据相关的操作,全都写到相关的 Model 中

4. 如何对记录进行排序 ⇧

user_mailer.rb中 validation_code = ValidationCode.find_by_email(email) 这样查找email存在问题

  • 比如同一个用户登录了10次,就创建了10个 validation_code,其中的 email 都是这个用户的
  • 需要找到最新的一个,代码中的逻辑就是需要在 find_by_email 前对 ValidationCode 做一个排序

app/mailers/user_mailer.rb

1
2
3
4
5
6
7
class UserMailer < ApplicationMailer
  def welcome_email(email)
    validation_code = ValidationCode.order(created_at: :desc).find_by_email(email)
    @code = validation_code.code
    mail(to: email, subject: "山竹记账验证码")
  end
end
  • `.order(created_at: :desc) 创建时间降序排列
  • find_by_email 只会找第一个
  • 找到最新的邮箱对应的验证码发送
  • 由于依赖了第三方服务,这个功能也是不好测试的

为什么要把 after_initialize 改为 before_create ⇧

  • 因为 after_initialize 会在每次初始化对象后执行
  • 而 before_create 只在创建数据库项目时执行,后者才是我们需要的

app/models/validation_code.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class ValidationCode < ApplicationRecord
  # email必填
  validates :email, presence: true
  # 钩子函数
  before_create :generate_code
  # 保存成功后执行
  after_create :send_email

  def generate_code
    self.code = SecureRandom.random_number.to_s[2..7]
  end

  def send_email
    UserMailer.welcome_email(self.email)
  end
end

5. 如何使用枚举处理kind为0 ⇧

使用控制台复现问题

  • bin/rails c
  • kind 是预留字段,用来区别验证码类型的,不仅登录,后续可扩展,重置密码等其他操作
  • 控制台输入 v1 = ValidationCode.create email: "1@qq.com", kind: "sign_in"
  • 之后控制台显示以下信息

    1
    2
    3
    4
    5
    6
    
    Loading 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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
ActiveRecord::Schema[7.2].define(version: 2026_09_10_063034) do
  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"
  # ...
  create_table "validation_codes", force: :cascade do |t|
    t.string "email"
    t.integer "kind", default: 1, null: false
    t.string "code", limit: 100
    t.datetime "used_at"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end
end
  • 使用 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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class ValidationCode < ApplicationRecord
  # email必填
  validates :email, presence: true
  # 钩子函数
  before_create :generate_code
  # 保存成功后执行
  after_create :send_email

  enum :kind, { sign_in: 0, reset_password: 1 }

  def generate_code
    self.code = SecureRandom.random_number.to_s[2..7]
  end

  def send_email
    UserMailer.welcome_email(self.email)
  end
end
  • 再次输入 v1 = ValidationCode.create email: "1@qq.com", kind: "sign_in"

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    
    3.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 做到了数据库不管是数字也好,字符串也好,写代码时不管是前端后端都可以用字符串,既满足了效率,又满足了方便

  • 查看数据库:

SELECT * FROM validation_codes LIMIT 100.png

  • 手动清空之前 ValidationCode 数据,控制台中运行 ValidationCode.destroy_all

     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
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    
    bin/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
    3
    
    3.1.2 :002 > ValidationCode.count
    ValidationCode Count (0.5ms)  SELECT COUNT(*) FROM "validation_codes"
    => 0

完整的输入控制台查看

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
bin/rails c                                                                                                no
Loading 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 (0.8ms)  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", "500716"], ["used_at", nil], ["created_at", "2026-11-23 13:28:26.034990"], ["updated_at", "2026-11-23 13:28:26.034990"]]
  TRANSACTION (3.2ms)  COMMIT
 =>
#<ValidationCode:0x0000767ec311bc88
...
3.1.2 :002 > v1
 =>
#<ValidationCode:0x0000767ec311bc88
 id: 7,
 email: "[FILTERED]",
 kind: "sign_in",
 code: "500716",
 used_at: nil,
 created_at: "2026-11-23 13:28:26.034990000 +0000",
 updated_at: "2026-11-23 13:28:26.034990000 +0000">
3.1.2 :003 > v1.kind
 => "sign_in"
  • 控制台可以随时改变,输入 v1.kind = 1
  • Rails自动帮你匹配,既可以输入数字,又可以输入字符串
  • Rails发现数字,就帮你翻译成字符串,发现使用字符串,就翻译成数字

    1
    2
    3
    4
    5
    6
    7
    8
    
    3.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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Api::V1::ValidationCodesController < ApplicationController
  def create
    # 查找60秒内创建的 ValidationCode
    ValidationCode.where(email: params[:email], kind: "sign_in", created_at: 1.minutes.ago..Time.now)
    validation_code = ValidationCode.new email: params[:email], kind: "sign_in"
    if validation_code.save
      render status: 200
    else
      render json: { errors: validation_code.errors }, status: 422
    end
  end
end
  • 查找60秒内创建的 ValidationCode
    • ValidationCode.where(email: params[:email], kind: "sign_in", created_at: 1.minutes.ago..Time.now)

或者改用检测是否有 ValidationCode 的 api

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Api::V1::ValidationCodesController < ApplicationController
  def create
    # 查找60秒内创建的 ValidationCode
    if ValidationCode.exists?(email: params[:email], kind: "sign_in", created_at: 1.minutes.ago..Time.now)
      render status: :too_many_requests # 429
      return
    end
    validation_code = ValidationCode.new email: params[:email], kind: "sign_in"
    if validation_code.save
      render status: 200
    else
      render json: { errors: validation_code.errors }, status: 422
    end
  end
end
  • exists?:Ruby里面有一个特点,如果函数返回值的类型是布尔,那么这个函数的结尾就是个问号
  • 这个问号是函数名的一部分

参考

使用 Ruby 中的if语法糖 app/controllers/api/v1/validation_codes_controller.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Api::V1::ValidationCodesController < ApplicationController
  def create
    # 查找60秒内创建的 ValidationCode
    return render status: :too_many_requests if
      ValidationCode.exists?(email: params[:email], kind: "sign_in", created_at: 1.minutes.ago..Time.now)
    validation_code = ValidationCode.new email: params[:email], kind: "sign_in"
    if validation_code.save
      render status: 200
    else
      render json: { errors: validation_code.errors }, status: 422
    end
  end
end

7. 两种测试:acceptance 和 requests ⇧

实现验证码基本测试 ⇧

如何测试多次请求

  • 发了一次请求,再 do_request 即可

spec/acceptance/validation_codes_spec.rb

  • 先让测试错一次,状态码改为 422
  • 运行 bin/rake docs:generate

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    
    require '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

测试结果

 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
27
bin/rake docs:generate                                                                                                                                                       no
/usr/local/rvm/rubies/ruby-3.1.2/bin/ruby -I/usr/local/rvm/gems/ruby-3.1.2/gems/rspec-core-3.13.6/lib:/usr/local/rvm/gems/ruby-3.1.2/gems/rspec-support-3.13.7/lib /usr/local/rvm/gems/ruby-3.1.2/gems/rspec-core-3.13.6/exe/rspec --pattern spec/acceptance/\*\*/\*_spec.rb --format RspecApiDocumentation::ApiFormatter
Generating API Docs
  Items
  GET /api/v1/items
    * Listing items
  验证码api
  POST /api/v1/validation_codes
    ! 请求发送验证码 (FAILED)

Failures:

  1) 验证码api POST /api/v1/validation_codes 请求发送验证码
     Failure/Error: expect(status).to eq 422

       expected: 422
            got: 429

       (compared using ==)
     # ./spec/acceptance/validation_codes_spec.rb:14:in `block (3 levels) in <main>'

Finished in 0.08892 seconds (files took 0.50356 seconds to load)
2 examples, 1 failure

Failed examples:

rspec ./spec/acceptance/validation_codes_spec.rb:8 # 验证码api POST /api/v1/validation_codes 请求发送验证码
  • 再改为 429,运行 bin/rake docs:generate

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    
    require '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

测试结果

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Generating API Docs
  Items
  GET /api/v1/items
    * Listing items
  验证码api
  POST /api/v1/validation_codes
    * 请求发送验证码

Finished in 0.09382 seconds (files took 0.50804 seconds to load)
2 examples, 0 failures

实现验证码其他功能测试 ⇧

目前查看文档,会显示错误的状态码 Status 429 too many request

  • 因为最后发的请求处理结果为 429
  • 需要区别对待两种不同的测试
    • 一种是 acceptance,可接受代码的测试
    • 一种是 reuests 其他测试

spec/requests/validation_codes_spec.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
require 'rails_helper'

RSpec.describe "ValidationCodes", type: :request do
  describe "验证码" do
    it "可以被发送" do
      post '/api/v1/validation_codes', params: { email: 'xmasuhai@163.com' }
      expect(response).to have_http_status(200)
    end
    it "发送太频繁就会返回429" do
      post '/api/v1/validation_codes', params: { email: 'xmasuhai@163.com' }
      expect(response).to have_http_status(200)
      post '/api/v1/validation_codes', params: { email: 'xmasuhai@163.com' }
      expect(response).to have_http_status(429)
    end
  end
end
  • 这次需要使用命令 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
  • 文章链接:
  • 版权声明
  • 非自由转载-非商用-非衍生-保持署名