← Back to Upcase

What are the pros and cons of using before blocks?


(charlieanna) #1

I have used a before(:all) to create some objects in the database and an after(:all) block to destroy them but I see that using before blocks and after blocks are a bad practice. Any reasons for this?

I need to destroy them because I have a presence validation of email on them.


(Ben Orenstein) #2

Can you link to something that says they’re a bad practice?

I don’t have any problem with them as tools, in general.

That said, needing to manually destroy objects during your test’s teardown phase seems like a smell. You should be able to get the whole database cleaned for you automatically. Not sure why something like database_cleaner can’t solve that for you.


(charlieanna) #3

This was suggested in the cheat sheat provided by thoughtbot along with the TDD workshop.


(Bruno Bruno) #4

One common problem with before(:all) is that the tests might become flaky as the order of the tests might impact the end result.

before(:all) do
  @user = FactoryGirl.create(:user, 'Old Name')
end

it '' do
  @user.name = 'New Name'
end

it '' do
  puts @user.name
end

The output of the second test depends on whether ir ran before or after the other test.