rails rspec before all vs before each

before(:all) runs the block one time before all of the examples are run.

before(:each) runs the block one time before each of your specs in the file

before(:all) sets the instance variables @admission, @project, @creative, @contest_entry one time before all of the it blocks are run.

However, :before(:each) resets the instance variables in the before block every time an it block is run.

Its a subtle distinction but important

again,

before(:all)
#before block is run
it { should belong_to(:owner).class_name('User') }
it { should belong_to(:project) }
it { should have_many(:entry_comments) }

it { should validate_presence_of(:owner) }
it { should validate_presence_of(:project) }
it { should validate_presence_of(:entry_no) }
it { should validate_presence_of(:title) }

before(:each)
# before block
it { should belong_to(:owner).class_name('User') }
# before block
it { should belong_to(:project) }
# before block
it { should have_many(:entry_comments) }
# before block

# before block
it { should validate_presence_of(:owner) }
# before block
it { should validate_presence_of(:project) }
# before block
it { should validate_presence_of(:entry_no) }
# before block
it { should validate_presence_of(:title) }

An important detail of before :all is that it's not DB transactional. I.e, anything within the before :all persists to the DB and you must manually tear down in the after :all method.

Implications mean that after test suites have completed, changes are not reverted ready for later tests. This can result in complicated bugs and issues with cross contamination of data. I.e, If an exception is thrown the after :all callback is not called.

However, before: each is DB transaction.

A quick test to demonstrate:

1. Truncate your appropriate DB table then try this,

  before :all do
    @user = Fabricate(:user, name: 'Yolo')
  end

2. Observe database afterwards the model remains persisted!

after :all is required. However, if an exception occurs in your test this callback will not occur as the flow was interrupted. The database will be left in an unknown state which can be especially problematic with CI/CD environments and automated testing.

3. now try this,

  before :each do
    @user = Fabricate(:user, name: 'Yolo')
  end

4. Now the database remains devoid of data after the test suite is complete. Far better and leaves us with a consistent state after tests run.

In short, before :each, is probably what you want. Your tests will run slightly slower, but it's worth the expense.

Detail here: https://relishapp.com/rspec/rspec-rails/docs/transactions See: Data created in before(:all) are not rolled back

Hope that helps another weary traveller.