19
12

More than 3 years have passed since last update.

shoulda-matchersが便利すぎる

Posted at

はじめに

RSpecを書くときに、shoulda-matchersというGemを使うと非常に便利でした。

shoulda-matchersとは

Shoulda Matchers provides RSpec- and Minitest-compatible one-liners to test common Rails functionality that, if written by hand, would be much longer, more complex, and error-prone.

Shoulda Matchersは、手書きで書くと長くて、複雑で、エラーが起きやすいRailsのテストをワンライナーにします。(意訳)
ワンライナーって1行ってことでいいのでしょうか...

使用方法

このようなuserモデルに対し、

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

shoulda-matchersを使うとこのようなRSpecを書くことができます!

user_spec.rb
require 'rails_helper'

RSpec.describe User, type: :model do
  it { is_expected.to validate_presence_of(:name) }
  it { is_expected.to have_many(:topics) }
end

バリデーションやアソシエーションのテストを一行で書けるのは便利すぎますね。
普通のRSpecの書き方で書いて、テストケースに抜けや漏れが出てしまうなんてことを防げます。

上記の例ではpresencehas_manyを取り上げましたが、他にも使えそうな書き方がたくさんあるので追記していきたいと思います。

参考:Shoulda-MatchersのREADME

19
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
12