9

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

I am already using rspec with factory girl.

Thanks, Hare

Hare Ram
  • 743
  • 2
  • 7
  • 19

3 Answers3

7

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

VAD
  • 2,351
  • 4
  • 20
  • 32
  • Actually in my spec/controllers fold has many controllers, i want clean my database before running each controllers. – Hare Ram Jan 28 '17 at 16:23
  • 1
    One should clean their database before executing each test. It's necessary to ensure that the test executed previously did not affect the testing environment prepared for the current test e.g. there was not any garbage in your test database. – VAD Jan 28 '17 at 17:17
  • Why do you need to set the strategy `before :each`? Isn't `before :suite` sufficient? – CyberMew Aug 03 '18 at 05:47
  • To clean your database after each test so the next test could use clean database without garbage from the previous test. The idea is you need to run every single test on a clean setup – VAD Aug 03 '18 at 07:13
3

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

0

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.

Midwire
  • 1,090
  • 8
  • 25