コード日進月歩

しんくうの技術的な小話、メモ、つれづれ、など

RSpecのitはブロックにしないことにより、箇条書きリストとして使うことができる

先日のt_wadaさんのライブコーディングで得た知見

環境

rspec (3.7.0)

概要

itはブロックを設けないことにより、pendingになるので、箇条書きとして機能する

例えば以下のようなUserモデルがあったとき

# == Schema Information
#
# Table name: users
#
#  id         :bigint(8)        not null, primary key
#  name       :string(255)
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class User < ApplicationRecord
end

こんなモデルへのテストを以下のように考える

  • 名前の長さは10文字以下
  • 名前には英語しか使えない
  • 名前には数字は使えない

そしてテストを書くときに以下のように書くと良い

require 'rails_helper'

RSpec.describe User, type: :model do

  it "名前の長さは10文字以下"
  it "名前には英語しか使えない"
  it "名前には数字は使えない"
end

こんな感じに書くと

$ bundle exec rspec spec/models/user_spec.rb 
***

Pending: (Failures listed here are expected and do not affect your suite's status)

  1) User 名前の長さは10文字以下
     # Not yet implemented
     # ./spec/models/user_spec.rb:15

  2) User 名前には英語しか使えない
     # Not yet implemented
     # ./spec/models/user_spec.rb:16

  3) User 名前には数字は使えない
     # Not yet implemented
     # ./spec/models/user_spec.rb:17

このようにpendingになるので、足りてないものを書くときに気づくことができるので、TDDに最適。

関連リンク