Posted almost 5 years ago. Visible to the public.

Using before(:all) in RSpec will cause you lots of trouble unless you know what you are doing

TL;DR Avoid before(:all), use before(:each) instead.

If you do use before(:all), you need to know what you are doing and take care of any cleanup yourself.

Why?

Understand this:

  • before(:all) is run when the context/describe block begins,
  • before(:all) is run outside of transactions, so data created here will bleed into other specs
  • before(:each) is run before each spec inside it,

Generally, you'll want a clean setup for each spec so that they are independent of other specs in the same context.

Example

Consider this spec:

Copy
describe User, 'something' do before :all do @user = User.make end it 'should so something' do # ... end it 'should so something else' do # ... end end

If you do that, @user will not be re-created for each test. Obviously, this has significant downsides, mostly that changes of one test on that record will bleed into the next one. \
Also, when using DatabaseCleaner with the :deletion strategy, the record will be gone after the first spec.

Doing it right

before(:each) is the right choice in most cases. So, for the above example we say the following and all is well.

Copy
describe User, 'something' do before :each do @user = User.make end # ... end

Furthermore, you will probably run into trouble with your RSpec configuration block that does things in config.before(:each), as this will also be run after your individual spec's before(:all) block did things and might revert changes.

Always use before(:each) unless you are totally sure of the impact your before(:all) block has.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Author of this card:

Avatar
Arne Hartherz
Last edit:
about 1 year ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandropedia