読者です 読者をやめる 読者になる 読者になる

RSpec(1.3.2)のGlobal after and before

RSpec(1.3.2)のGlobal after and beforeについて調べたメモです。
(今さら1.3.2って。。)

  • すべてのexamplesで共通に適用されるbefore/afterを書くことができる。spec_helper.rbにSpec::Runner.configureで書くのがふつう。
  • before/afterの実行ポイントはsuite、all、eachを指定できる。
  • Specファイル単位のbefore/afterは用意されていない。

Specファイル単位のbefore/afterを書きたかったので、調べたのですが、やっぱりないんですね。。やっぱりファイル単位みたいな考え方はないということで。。ファイルをロードするところで無理矢理突っ込むしかないかなあ。。


spec_helper.rb

Spec::Runner.configure do |config|
  config.before(:suite) { puts '[Config] before suite'}
  config.before(:all) { puts '[Config] before all'}
  config.before(:each) { puts '[Config] before each'}
  config.after(:suite) { puts '[Config] after suite'}
  config.after(:all) { puts '[Config] after all'}
  config.after(:each) { puts '[Config] after each'}
end

hoge_spec.rb

require './spec_helper'

describe 'Hoge' do
  before(:all) do
    puts '[Hoge] before all'
  end 

  before do
    puts '[Hoge] before each'
  end 

  after do
    puts '[Hoge] after each'
  end 

  it 'example1' do
    puts 'example1'
  end 

  it 'example2' do
    puts 'example2'
  end 

  after(:all) do
    puts '[Hoge] after all'
  end 
end

fuga_spec.rb

require './spec_helper'

describe 'Fuga' do
  before(:all) do
    puts '[Fuga] before all'
  end 

  before do
    puts '[Fuga] before each'
  end 

  after do
    puts '[Fuga] after each'
  end 

  it 'example1' do
    puts 'example1'
  end 

  it 'example2' do
    puts 'example2'
  end 

  after(:all) do
    puts '[Fuga] after all'
  end 
end

実行結果

ootas-MacBook-Air@sogo:rspec-exam $ spec hoge_spec.rb fuga_spec.rb 
[Config] before suite
[Config] before all
[Hoge] before all
[Config] before each
[Hoge] before each
example1
[Hoge] after each
[Config] after each
.[Config] before each
[Hoge] before each
example2
[Hoge] after each
[Config] after each
.[Hoge] after all
[Config] after all
[Config] before all
[Fuga] before all
[Config] before each
[Fuga] before each
example1
[Fuga] after each
[Config] after each
.[Config] before each
[Fuga] before each
example2
[Fuga] after each
[Config] after each
.[Fuga] after all
[Config] after all


Finished in 0.024466 seconds

4 examples, 0 failures
[Config] after suite