Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 536
Hare Ram Avatar asked Jan 28 '17 16:01

Hare Ram


2 Answers

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

like image 179
VAD Avatar answered Oct 19 '22 20:10

VAD


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

like image 45
Venkateshwara Cholan Avatar answered Oct 19 '22 19:10

Venkateshwara Cholan