RSpec での metadata の活用法についての覚書
Published: 2020/1/27
概要
metadata とは、任意のキーに対して値を各 example (example
や it
で定義される、実際にテストを行うブロック) に対して
付与することができる機構。
に、その定義方法と、各 example 内部での利用方法などが記述されている。
具体的に使用例を引用すると、以下のようになる。
RSpec.describe "a group with user-defined metadata", :foo => 17 do
it 'has access to the metadata in the example' do |example|
expect(example.metadata[:foo]).to eq(17)
end
it 'does not have access to metadata defined on sub-groups' do |example|
expect(example.metadata).not_to include(:bar)
end
describe 'a sub-group with user-defined metadata', :bar => 12 do
it 'has access to the sub-group metadata' do |example|
expect(example.metadata[:bar]).to eq(12)
end
it 'also has access to metadata defined on parent groups' do |example|
expect(example.metadata[:foo]).to eq(17)
end
end
end
利用方法
RSpec の機能に対して、 metadata が一致する場合のみに適用する、といった機能がいくつか提供されている模様。 自分の知る限り、有効そうだと思った活用法は次の2つ。
その1
のように、before
や after
を条件的に実行できる。
これを実際に活用し、 DatabaseCleaner の strategy の切り分けに使っているのが次のリンク。
その2
上記では、include_context
を、 metadata が一致したテストでだけ実行するようにする設定について書かれている。
Tags: rspec
関連記事
RSpec の mock の際に、任意のコードを実行する
2023/6/3