昨天我们已经写出了第一篇测试 今天我们就要来依靠 Shoulda Matchers 来简化以及优化我们的测试
group :test do
gem 'shoulda-matchers', '~> 5.0'
end
然後跑 bundle install
他也告诉你他帮你多了好几种 matchers 在官方文件上都查得到
将以下 code 放到 spec/rails_helper.rb
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
在底下也有告诉你基础运用
# RSpec
RSpec.describe MenuItem, type: :model do
describe 'associations' do
it { should belong_to(:category).class_name('MenuCategory') }
# 测试关联性
end
describe 'validations' do
it { should validate_presence_of(:name) }
# 测试是否为必填
it { should validate_uniqueness_of(:name).scoped_to(:category_id) }
# 测试是否是唯一值
end
end
我们就来优化一下昨天写的测试吧!
require 'rails_helper'
RSpec.describe User, type: :model do
describe 'validations' do
context 'name must be present' do
it { should validate_presence_of(:name) }
# 等同於
# subject.should validate_presence_of(:name)
# it { is_expected.to validate_presence_of(:name) }
end
end
end
这行就可以直接拿来测 name 是不是有限制要必填,刚刚写了这麽多但 Shoulda Matchers 一行就帮你搞定!
我们可以试着把 validates :name, presence: true
拔掉跑一次测试不会过
$ rspec spec/models/user_spec.rb
F
Failures:
1) User validations name must be present is expected to validate that :name cannot be empty/falsy
Failure/Error: it { should validate_presence_of(:name) }
Expected User to validate that :name cannot be empty/falsy, but this
could not be proved.
After setting :name to ‹""›, the matcher expected the User to be
invalid, but it was valid instead.
# ./spec/models/user_spec.rb:6:in `block (4 levels) in <top (required)>'
Finished in 0.06186 seconds (files took 2.86 seconds to load)
1 example, 1 failure
再放回去测试就会通过搂!
$ rspec spec/models/user_spec.rb
.
Finished in 0.0644 seconds (files took 3.86 seconds to load)
1 example, 0 failures
Shoulda Matchers 最主要是拿来测试 model 关联性以及验证 可以节省很多 code,其实还有很多语法可以使用在这边就不多赘述了官方文件写的挺详细的!
在官方也有提及这两种是否有差别,答案是没有。只是现在更流行使用expect
在 betterspec也有说到目前主流使用expect
明天先来介绍 before
、after
!再来讲 let
、let!
、subject
!
昨天我们讨论的函式,是没有返回数值的函式,只是单纯传入参数做运算後,直接输出。但我们更多时候会需要把...
感觉还是有bug,他会一直买停不下来,可能要再找一两天请假来盯着机器人,然後上线前下单的金钱限制要设...
当我们在建立单据与发票的时候,若想要自定义流水号该怎麽在ODOO里面设定呢? 我们以invoice单...
在昨天的铁人贴文中制作了交易建立的画面,之前也有提到,透过批次,会於日档批次中,定期抓取历史缴费纪录...
使用时机: 1. 资料库效能慢的时候 2. 就是想读写分离的时候 主从分别叫做Master, Sla...