こんにちは!kossyです!
さて、今回は、特定のテストケースを実行したい時に便利な、
focus: trueオプションの使い方について、ブログに残してみたいと思います。
環境
Rails 5.1.6
Ruby 2.5.1
rspec 3.8.0
MacOS Mojave
まずはspec_helper.rbに設定
以下の記述を追記します。
/spec/spec_helper.rb RSpec.configure do |config| 省略 config.filter_run :focus end
これでfocus: trueを使えるようになります。
後は実行したいブロックに記述するだけ
例えばこんなテストがあったとします。
describe 'Validation of create User' do describe 'blank' do it '名前が空白だとエラーになる' do user = User.new(name: '', email: 'example@gmail.com', password: 'test1234', password_confirmation: 'test1234') user.valid? expect(user.errors[:name]).to include('を入力してください') end it 'メールアドレスが空白だとエラーになる' do user = User.new(name: 'テストユーザー', email: '', password: 'test1234', password_confirmation: 'test1234') user.valid? expect(user.errors[:email]).to include('を入力してください') end it 'パスワードが空白だとエラーになる' do user = User.new(name: 'テストユーザー', email: '') user.valid? expect(user.errors[:password]).to include('を入力してください') end end
では、一つ目のitブロックにfocus: trueを設定します。すると、
$ bundle exec rspec spec/models/user_spec.rb User Validation of create User blank 名前が空白だとエラーになる Finished in 0.24428 seconds (files took 10.93 seconds to load) 1 example, 0 failures
一つ目のテストブロックのテストのみ実行されます。
describeのブロックにも設定することができます。
$ bundle exec rspec spec/models/user_spec.rb describe 'Validation of create User', focus: true do describe 'blank' do it '名前が空白だとエラーになる' do user = User.new(name: '', email: 'example@gmail.com', password: 'test1234', password_confirmation: 'test1234') user.valid? expect(user.errors[:name]).to include('を入力してください') end it 'メールアドレスが空白だとエラーになる' do user = User.new(name: 'テストユーザー', email: '', password: 'test1234', password_confirmation: 'test1234') user.valid? expect(user.errors[:email]).to include('を入力してください') end it 'パスワードが空白だとエラーになる' do user = User.new(name: 'テストユーザー', email: '') user.valid? expect(user.errors[:password]).to include('を入力してください') end end 以下はログ User Validation of create User blank 名前が空白だとエラーになる メールアドレスが空白だとエラーになる パスワードが空白だとエラーになる Finished in 0.15704 seconds (files took 8.86 seconds to load) 3 examples, 0 failures
Validation of create Userのdescribeブロックのテストが全て実行されているのがわかります。
テストケースが増えてくると実行して終了するまで待つのが
とても面倒になってきます。
focus: trueはそんなシチュエーションで活躍間違いなしのオプションです。
参考にさせていただいた記事
RSpecで特定のテストケースのみを実行する方法 - TIM Labs
今日から使える! RSpec でテストの実行サンプル it を素早く絞り込み・スキップする方法 - Qiita