Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

RSpec | rspec config | alias_example_to

概要

rspec config | alias_example_to

詳細

RSpec.configureのalias_example_toを利用すると
it(example, specify)やdescribe(context)にエイリアスを追加できます。

利用目的としては

・単純に好みの名前を付ける
・特定のオプションと併せて定義できる点を利用して
オプション+エイリアスで利用する。
この利用方法はRSpecが「pending」「xexample」などを定義しているのと同じです。
RSpec本家のソースコードが気になる方は下記のコード内を「xexample」などで検索してみてください
https://github.com/rspec/rspec-core/blob/master/lib/rspec/core/example_group.rb

など。
特にオプションと組み合わせる使い方は独自に定義したオプションなどと組み合わせると便利そうです。
例えば、一部のexampleのみテストと同時に画面キャプチャも行いたい場合に
画面キャプチャの有無をオプション化し、
オプションをtrueに設定したaliasをcapture_itなどと命名する・・・など。

※最新のGitHubRSpecソースコードを見るとalias_example_group_toも追加されているので
describeやcontextのエイリアスも追加できるようです。

サンプル仕様

itのエイリアスとして「例」を追加。

hige_spec.rb

require 'spec_helper'
require 'hige'

describe Hige do
  context "hige1", :hige1 => "hige1_outer" do"hige1", :hige1 => "hige1_inner" do
      expect("hige1_inner").to eq(example.metadata[:hige1])
    end
  end"hige2", :hige2 => "hige2" do
    expect("hige2").to eq(example.metadata[:hige2])
  end
end

spec_helper.rb

RSpec.configure do |config|
  config.treat_symbols_as_metadata_keys_with_true_values = true
  config.run_all_when_everything_filtered = true
  config.filter_run :focus
  config.alias_example_to :例
end

実行結果

$ rspec
Run options: include {:focus=>true}

All examples were filtered out; ignoring {:focus=>true}
case hige2
.case hige1
.

Finished in 0.001 seconds
2 examples, 0 failures