Hare Ram
Hare Ram

Reputation: 783

how to clean database before running the each spec file?

I want to clear my test database before running the each spec files.

I am already using rspec with factory girl.

Thanks, Hare

Upvotes: 9

Views: 5493

Answers (3)

Venkateshwara Cholan
Venkateshwara Cholan

Reputation: 43

In your spec_helper.rb, inside the RSpec.configure block

RSpec.configure do |config|

  # ...

  config.before(:suite) do
    DatabaseCleaner.clean_with :transaction
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:all) do
    DatabaseCleaner.start
  end

  config.after(:all) do
    DatabaseCleaner.clean
  end

  # ...
end

before(:all) and after(:all) runs for every spec file and not before and after the whole suite. So, for every spec file you will be able to clear database using any of the three strategies :transaction, :truncation, :deletion

Upvotes: 3

Midwire
Midwire

Reputation: 1100

This is what I typically do for DatabaseCleaner

# Database Cleaner
config.before(:suite) do
  DatabaseCleaner.strategy = :transaction
  DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
  DatabaseCleaner.start
end
config.after(:each) do
  DatabaseCleaner.clean
end

That will make sure you have a clean database for each test.

Checkout a related, albeit old, article by Avdi for more info.

Upvotes: 0

VAD
VAD

Reputation: 2401

Add to RSpec.configure block in your spec_helper.rb

  config.before(:suite) do
    DatabaseCleaner.clean_with :truncation
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

Must work

Upvotes: 8

Related Questions