56

I am wondering whether the before (as seen below) is the same as before :all in RSpec. Sometimes neither :each nor :all is specified and it confuses me as to what before actually does.

require 'spec_helper'

describe "this is a description" do 
  before do # vs. before :all or before :each
   # do something...
  end
end

Would appreciate if anyone can explain the differences, if any. Thanks!

Jonathan Lin
  • 19,922
  • 7
  • 69
  • 65

1 Answers1

99

So the answer is No. before is equivalent to before :each, not before :all

Test example.

Update: Wow, this question is popular. To save your head from cognitive overload, I suggest you explicitly state :each or :all.

Jonathan Lin
  • 19,922
  • 7
  • 69
  • 65
  • I want to add that if you nest before contexts without specific runtime like before(:each) it will NOT override the upper level before hooks. You can then nest hooks and add code to the pile but be careful as this could cause you problems. – Alexis Rabago Carvajal Aug 01 '18 at 03:38
  • 3
    I bet this is particularly popular because the rspec doc page for before doesn't mention the default. https://relishapp.com/rspec/rspec-core/v/2-2/docs/hooks/before-and-after-hooks – cdmo Mar 03 '20 at 19:18