LoginSignup
2
2

More than 1 year has passed since last update.

rspec の設定でタグ指定の有無を判定する

Last updated at Posted at 2018-04-26

こんな感じ

RSpec.configure do |config|
  if config.filter.rules[:some_tag]
    # do something
  else
    # do something
  end
end

ユースケース

「特定のタグが指定されなかった時」に「全ての処理にbeforeのフックを入れたい場合」に利用した。

次のような before でのタグ指定は、
「rspecコマンドで特定のタグが指定されなかった時に、フックが実行される」のではなく、
「特定のタグが false 指定のテストが走る時に、フックも実行される」という動作のため。

before :example, some_tag: false do
  # do something
end

検証コード例

RSpec.configure do |config|
  # RUN CASES
  # rspec this_script.rb --tag=some_tag
  if config.filter.rules[:some_tag]
    puts 'FOUND some_tag'

    config.before :example do
      puts 'BEFORE WHEN some_tag FOUND'
    end
  # RUN CASES
  # rspec this_script.rb
  # rspec this_script.rb --tag=another_tag
  # rspec this_script.rb --tag=~some_tag ( exclude some_tag )
  else
    puts 'NOT FOUND some_tag'

    config.before :example do
      puts 'BEFORE WHEN some_tag NOT FOUND'
    end
  end

  # When specify no tags
  # This before do not run in "RUN WHEN some_tag: true" describe
  config.before :example, some_tag: false do
    puts 'BEFORE WHEN some_tag FALSE'
  end
end

RSpec.describe do
  describe 'RUN WHEN some tag: true', some_tag: true do
    subject { true }
    it { is_expected.to be true }
  end

  describe 'RUN WHEN some_tag: false', some_tag: false do
    subject { true }
    it { is_expected.to be true }
  end
end

実行例

some_tag: false が指定されていないテスト ( describe 内 )でも、before 処理が実行されているのが分かる。

$ bundle exec rspec -fd rspec/tags_existence_in_configure.rb

NOT FOUND some_tag


  RUN WHEN some tag: true
BEFORE WHEN some_tag NOT FOUND
    should equal true
  RUN WHEN some_tag: false
BEFORE WHEN some_tag NOT FOUND
BEFORE WHEN some_tag FALSE
    should equal true

Finished in 0.00881 seconds (files took 0.56641 seconds to load)
2 examples, 0 failures

環境

RSpec 3.7
  - rspec-core 3.7.1
  - rspec-expectations 3.7.0
  - rspec-mocks 3.7.0
  - rspec-support 3.7.1

Gist

参考

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

2
2
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
2
2