how to clean database before running the each spec file?
Asked Answered
S

3

9

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

I am already using rspec with factory girl.

Thanks, Hare

Syncom answered 28/1, 2017 at 16:10 Comment(2)
Are you using database_cleaner gem?Gause
Yes, I am using it. But not sure how to write for each file.Syncom
U
8

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

Undertenant answered 28/1, 2017 at 16:20 Comment(4)
Actually in my spec/controllers fold has many controllers, i want clean my database before running each controllers.Syncom
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.Undertenant
Why do you need to set the strategy before :each? Isn't before :suite sufficient?Counterweigh
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 setupUndertenant
I
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

Intinction answered 4/7, 2019 at 12:34 Comment(2)
? This looks just like @VAD's answer from Jan 28, 2017.Delirious
VAD's answer will clean database for every single test case, mine does it for every single spec file(which was the actual question). the difference is :all instead of :eachIntinction
N
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.

Nerine answered 31/1, 2017 at 17:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.