rails rspec before all vs before each

Ruby on-RailsRspec

Ruby on-Rails Problem Overview


contest_entry_spec.rb

    require 'spec_helper'
    
    describe ContestEntry do
      
      before(:all) do
        @admission=Factory(:project_admission)
        @project=Factory(:project_started, :project_type => @admission.project_type)
        @creative=Factory(:approved_creative, :creative_category => @admission.creative_category)
        @contest_entry=Factory(:contest_entry, :design_file_name => 'bla bla bla', :owner => @creative, :project => @project)
      end
      
      context 'non-specific tests' do
        subject { @contest_entry }
        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) }
    
      end
end

When I run these tests everything is okey but if I change before(:all) to before(:each) every test will be failed.I don't know why it happens?

This is the error

 Failure/Error: @contest_entry=Factory(:contest_entry, :design_file_name => 'bla bla bla', :owner => @creative, :project => @project)
     ActiveRecord::RecordInvalid:
       Validation Failed: User is not allowed for this type of project

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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) }

Solution 2 - Ruby on-Rails

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.

Solution 3 - Ruby on-Rails

before(:all), which ensures that the sample users are created once, before all the tests in the block. This is an optimization for speed.

Solution 4 - Ruby on-Rails

One thing to note is by default before use before(:each), also in before(:all) the controller instance is not set so the controller methods like request not used.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnny CashView Question on Stackoverflow
Solution 1 - Ruby on-RailsfontnoView Answer on Stackoverflow
Solution 2 - Ruby on-Railswired00View Answer on Stackoverflow
Solution 3 - Ruby on-RailsJazib BashirView Answer on Stackoverflow
Solution 4 - Ruby on-Railsshiva kumarView Answer on Stackoverflow