iT邦幫忙

2021 iThome 鐵人賽

DAY 5
0
自我挑戰組

Rails測試寫起乃!!!系列 第 5

Day05 測試寫起乃 - Shoulda Matchers

  • 分享至 

  • xImage
  •  

昨天我們已經寫出了第一篇測試 今天我們就要來依靠 Shoulda Matchers 來簡化以及優化我們的測試

安裝 Shoulda Matchers

Shoulda Matchers github

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

應用 Shoulda Matchers

我們就來優化一下昨天寫的測試吧!

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,其實還有很多語法可以使用在這邊就不多贅述了官方文件寫的挺詳細的!

Should vs is_expected.to

在官方也有提及這兩種是否有差別,答案是沒有。只是現在更流行使用expectbetterspec也有說到目前主流使用expect

明天先來介紹 beforeafter!再來講 letlet!subject


上一篇
Day04 測試寫起乃 - 撰寫Rspec
下一篇
Day06 測試寫起乃 - before、after
系列文
Rails測試寫起乃!!!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言