Day04 测试写起乃 - 撰写Rspec

在上一篇我们已经安装好 rspec 也产出了 User model 接下来就开始尝试写测试搂!

我在 User 上多了几个栏位接下来就可以针对以下栏位来做测试

2.6.6 :003 > User
 => User(id: integer, created_at: datetime, updated_at: datetime,
         name: string, email: string, phone: integer)

Rspec 基本架构

我们可以先思考 name 这个栏位为必填的话测试可以怎麽写?

require 'rails_helper'

RSpec.describe User, type: :model do
  describe 'validations' do
    context 'name must be present' do
      it 'is not valid without a name' do
        user = User.new(phone: '123', email: '[email protected]')
        expect(user).not_to be_valid
      end

      it 'is valid with a name' do
        user = User.new(name: 'ck', phone: '123', email: '[email protected]')
        expect(user).to be_valid
        expect(user.name).to eq('ck')
      end
    end
  end
end

用上述例子可以看到有很多陌生的专有名词,我们可以依依解释

type: :model => 指定type 为 model,当然也有 controller、view、request
describe => 就是字面上的意思描述此区域的测试要测的内容
context => 作用域其实与 describe 相同其实没有太多差异只是describe的别名,主要是区隔规格
it => 指每个测试案例
expect => 最常用到的语法也是每个测试的精髓,你期望哪些东西会等同於你想像的样子。比如:没有名字那就期望这个user在建立时就是无效的

对於describe与context差异的朋友可以看看这篇 describe vs. context in rspec

According to the rspec source code, “context” is just a alias method of “describe”, meaning that there is no functional difference between these two methods. However, there is a contextual difference that’ll help to make your tests more understandable by using both of them.

如果我们跑一下这个测试会发现测试没有通过

$ rspec spec/models/user_spec.rb

Failures:

  1) User validations name must be present is not valid without a name
     Failure/Error: expect(user).not_to be_valid
       expected #<User id: nil, created_at: nil, updated_at: nil, name: nil, email: "[email protected]", phone: 123> not to be valid
     # ./spec/models/user_spec.rb:8:in `block (4 levels) in <top (required)>'

Finished in 0.12145 seconds (files took 4.03 seconds to load)
2 examples, 1 failure

Failed examples:

rspec ./spec/models/user_spec.rb:6 # User validations name must be present is not valid without a name

当 user 没有 name 时应该要是无效的但他却建立出来了
这时就会知道应该是在 model 的地方没有补上 validate 导致测试没通过所以我们到 models/user.rb

# user.rb
class User < ApplicationRecord
  validates :name, presence: true
end

再跑一次测试 rspec spec/models/user_spec.rb

$ rspec spec/models/user_spec.rb
..

Finished in 0.12003 seconds (files took 4.19 seconds to load)
2 examples, 0 failures

我们第一个测试就大功告成了! 但也会发现怎麽建立起来这麽麻烦而且有重复的code 明天我们就使用 Shoulda Matchers 跟 FactoryBot 来优化测试吧!


<<:  为什麽87% 的资料科学专案没办法产品化? | MLOps落地指南 - 技术篇

>>:  [Day04] JavaScript - ES6 模板字符串 (Template Literal)

AE卷轴制作5-Day6

1.将要遮罩的Shape>Pre compose 2.最後就是最简单的部分,找张图用遮罩就完成...

[Day 29] 实作-axios 串接api

先看一下有哪些api 下面列出这次用到的openapi, 可以看到他有一个共通的domain htt...

Golang-Slice 使用copy()与宣告的不同

这篇算是笔记 看到有人发问slice有关的问题 有人回答用copy()进行复制slice,我就想跟用...

[jest] Guides - Timer Mocks

前言 在我们撰写jest的时候,常常会遇到source code的function有使用到setTi...

[Day 30]从零开始学习 JS 的连续-30 Days---连续30天的"遗憾赛程"!!

连续30天的"遗憾赛程"!! 谁说连续写30天就可以完赛啊!我连续写了30天,结...