LoginSignup
23
20

More than 5 years have passed since last update.

Rspecのbeforeとlet!の実行順序

Last updated at Posted at 2015-03-07

beforeとlet!の実行順序は、結論から言うと、同時であるため書いた順に実行される。

実行タイミング

beforeとlet!

どちらも、ブロックが定義された時に実行される。

let

ちなみにletは、変数が初めて使用された時だけ遅延評価され、specテストが終わるまでキャッシュとして使える。

beforeとlet!の実行順序

試されていた方がいたので、そちらを参考にする。

$count = 0

describe 'let!' do
  invocation_order = []

  before(:each) { invocation_order << :before1 }

  let!(:count) do
    invocation_order << :let!
    $count += 1
  end

  before(:each) { invocation_order << :before2 }

  it 'calls the helper method in a before hook in described order' do
    invocation_order << :example
    invocation_order.should == [:before1, :let!, :before2, :example]
    count.should == 1
  end
end
% rspec -cfs let_3.rb

let!
  calls the helper method in a before hook in described order

Finished in 0.00062 seconds
1 example, 0 failures

before(:each), let!(:count), before(:each)の順で実行したところ、そのままの順で評価されている。

なので、beforeと同じタイミングで上から順番に評価される模様。

参考

すごいぞRSpec(letとlet!編)

23
20
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
23
20