LoginSignup
15
15

More than 5 years have passed since last update.

今日から使える! RSpec でテストの実行サンプル it を素早く絞り込み・スキップする方法

Last updated at Posted at 2015-12-02

状況

RSpecでSpecを書く際、特定のexample(it)のみ実行したい場合、focus: タグを付けます。
(spec_helper での設定か、実行時オプションが必要です。後述)

it 'has 25 days', focus: true do
  expect(calendar.size).to eq(25)
end

ですが、絞り込みしたい時に毎回タイプするのが大変です。

対応

こういった時、it を focus に書き換えることが可能です。

focus 'has 25 days' do
  expect(calendar.size).to eq(25)
end

更に短縮形

it を消して focus に書き換える、これもまた面倒です。
こういったとき、 it の手前に focus の頭文字である f を付けた、fitという別名が用意されています。

特定のテストを実行したいときのみ、fをタイプし、終わったらfを消すという手順で、specを書きやすくなります。

fit 'has 25 days' do
  expect(calendar.size).to eq(25)
end

別名

it には、 example や specify という別名があり、文脈によって使い分けることが出来ますが、これらについても focus するための名前が用意されています。

fexample 'Advent calendar has 25 days' 
fspecify '師走は12月'

example のスキップ

同様に、特定のexampleのみテストから除外したい場合に :skip というタグが用意されていますが、

it 'has 25 days', skip: true do
  expect(calendar.size).to eq(25)
end

これらも it を skip, xit, xexample, xspecify に置き換えることでスキップできます。

skip 'has 25 days' 
xit 'has 25 days' 
xexample 'Advent calendar has 25 days' 
xspecify '師走は12月' 

xit 等では、素早く特定の example をスキップすることができます。
skip では、実行しない仕様であるという意思表示が可能です。

グループの除外、絞り込み

仕様テストのグループ(describe, context)についても、同様のショートカットが可能です。

# 古い仕様などをskip
xcontext 'サンタクロースを待つ時' 
xdescribe 'サンタクロースが来る'
# 絞り込み
fcontext '年末になった時' 
fdescribe '仕事を増やす' 

補足:spec_helper の設定

最初に生成される spec_helper ではコメントアウトされていますが、以下のオプションを有効にします。

spec_helper.rb
RSpec.configure do |config|
  config.filter_run :focus
  config.run_all_when_everything_filtered = true
end
15
15
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
15
15