Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec + database cleaner, not cleaning correctly

i really can't understand why DatabaseCleaner is not cleaning my test database. This is what i get prompting

1.9.2p290 :007 > DatabaseCleaner.clean

--

=> [#<DatabaseCleaner::Base:0x007fa7e4dd8b58 @autodetected=true, @orm=:active_record, @strategy=#<DatabaseCleaner::ActiveRecord::Transaction:0x007fa7e4dc14f8 @db=:default>>] 

This seems not to set correctly the database (supposed to be :test), so i got a solution like

 DatabaseCleaner[:active_record, :connection => :test].clean
 # => nil

The gem seems to be set up correctly:

1.9.2p290 :007 > DatabaseCleaner[:active_record, :connection => :test]

#<DatabaseCleaner::Base:0x007fe8fcfd4868 @orm=:active_record, @strategy=#<DatabaseCleaner::ActiveRecord::Transaction:0x007fe8fcfd2748 @db=:test, @connection_hash={"adapter"=>"sqlite3", "database"=>"db/test.sqlite3", "pool"=>5, "timeout"=>5000}>, @db=:test> 

This seems to setup correctly the test database, however it is still not going to clean properly the database. Any suggestions?

Thank you very much.

like image 899
Andrea Avatar asked Mar 29 '12 14:03

Andrea


4 Answers

Even with database cleaner correctly configured it is easy to leave data lying around.

config.before(:suite) do
  DatabaseCleaner.clean_with :truncation  # clean DB of any leftover data
  DatabaseCleaner.strategy = :transaction # rollback transactions between each test
  Rails.application.load_seed # (optional) seed DB
end

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

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

The configuration above starts & runs the cleaner either side of each test.

If you then use before :all in your specs you can end up with data lying around:

describe User do
  # Before all is outside the before :each 
  before :all do
    @user = User.create(:email => '[email protected]')
  end

  ...tests here
end
like image 95
Peter Avatar answered Nov 11 '22 06:11

Peter


Here's my spec_helper.rb (slightly modified) - maybe that will help you?

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'database_cleaner'

RSpec.configure do |config|
  config.before(:suite) do
    DatabaseCleaner.strategy = :truncation
  end
  config.before(:each) do
    DatabaseCleaner.start
  end
  config.after(:each) do
    DatabaseCleaner.clean
  end
end
like image 26
Jeppe Liisberg Avatar answered Nov 11 '22 06:11

Jeppe Liisberg


Avdi Grimm's had a nice post recently on configuring database cleaner:

http://devblog.avdi.org/2012/08/31/configuring-database_cleaner-with-rails-rspec-capybara-and-selenium/

like image 4
harlow Avatar answered Nov 11 '22 05:11

harlow


$ rails c test
> require 'database_cleaner'
> DatabaseCleaner.strategy = :truncation
> DatabaseCleaner.clean

https://github.com/DatabaseCleaner/database_cleaner

like image 1
Abel Pc Ag Avatar answered Nov 11 '22 06:11

Abel Pc Ag