Rspec create variables so that they can be used through out the file

Currently I am using this way to create my variables using FactoryGirl.

describe Push do

  before do
	  @user1 = FactoryGirl.create(:user, :device_identifier => "a9c72e102f1bc1b0")
	  @user2 = FactoryGirl.create(:user, :device_identifier => "7d94095209b6e051")
	  @user3 = FactoryGirl.create(:user, :device_identifier => "85718da6d39b75c5")
	  @user4 = FactoryGirl.create(:user, :device_identifier => "4BA905D6-443D-4631-A7BD-DEDEA1638BA1")
	  @user5 = FactoryGirl.create(:user, :device_identifier => "9dce6d95d8b1ae67")
	  @users = [@user1.jabber_id, @user2.jabber_id, @user3.jabber_id, @user4.jabber_id, @user5.jabber_id]
	  @push =, "Hi")

I think what before block does is cleans the database and creates new instances each time before every example.

But what would I do if I were to call that block only once instead of using the before block and then use the variables throughout the file?

I tried doing this but then I had to clean my test database every time I ran the spec file. I think this is because my test database was not getting cleaned after the file ran.

I tried using database_cleaner but failed there too.

And why is using the before block a bad practise?

I think you should start a new topic for this question.

And, again, things are rarely always good or always bad. A better way to phrase this is “what are the pros and cons of using before blocks?”

Have you tried using before(:all)?

Will before(:all) clean my database after all the examples have finished?

Or I can use after(:all) to destroy all the variables. I think this will work.

As @benorenstein suggested in your other post you normally shouldn’t be doing database cleaning manually. Have a look at DatabaseCleaner which does the job for you and integrates nicely with RSpec, Cucumber, …

Hi, you should definitely need to use the DatabaseCleaner as @lenartr mentioned, you should also use let or let!.

A real quick explanation and example.

let(:user){ FactoryGirl.create :user }

let creates the user until you call user

let! forces the object creation before each example, it doesn’t wait for the call to user. So it works like a before_each

An the most beautiful part… You don’t need to use the @ anywhere, because it is like a method call rather an instance variable.

You can find the example and a better explanation here:

Before you wrap everything in let or let! read this article not to abuse them :wink: Looking at your example code I’d also suggest you look if you could build object instead of creating them. Or even better use build_stubbed to avoid hitting the database and speed up your tests quite a bit. Looks like you pasted some code from unit test for Push model where you should test in isolation as much as possible. Maybe you should be doing some mocking and stubbing.