Code Monkey home page Code Monkey logo

database_cleaner's Introduction

Database Cleaner

Build Status Code Climate codecov Gem Version SemVer

Database Cleaner is a set of gems containing strategies for cleaning your database in Ruby.

The original use case was to ensure a clean state during tests. Each strategy is a small amount of code but is code that is usually needed in any ruby app that is testing with a database.

Gem Setup

Instead of using the database_cleaner gem directly, each ORM has its own gem. Most projects will only need the database_cleaner-active_record gem:

# Gemfile
group :test do
  gem 'database_cleaner-active_record'
end

If you are using multiple ORMs, just load multiple gems:

# Gemfile
group :test do
  gem 'database_cleaner-active_record'
  gem 'database_cleaner-redis'
end

List of adapters

Here is an overview of the databases and ORMs supported by each adapter:

MySQL, PostgreSQL, SQLite, etc

MongoDB

Redis

More details on available configuration options can be found in the README for the specific adapter gem that you're using.

For support or to discuss development please use the Google Group.

Discontinued adapters

The following adapters have been discontinued. Please let us know on the Google Group if you think one of these should be resurrected!

How to use

require 'database_cleaner/active_record'

DatabaseCleaner.strategy = :truncation

# then, whenever you need to clean the DB
DatabaseCleaner.clean

With the :truncation strategy you can also pass in options, for example:

DatabaseCleaner.strategy = [:truncation, only: %w[widgets dogs some_other_table]]
DatabaseCleaner.strategy = [:truncation, except: %w[widgets]]

(I should point out the truncation strategy will never truncate your schema_migrations table.)

Some strategies need to be started before tests are run (for example the :transaction strategy needs to know to open up a transaction). This can be accomplished by calling DatabaseCleaner.start at the beginning of the run, or by running the tests inside a block to DatabaseCleaner.cleaning. So you would have:

require 'database_cleaner/active_record'

DatabaseCleaner.strategy = :transaction

DatabaseCleaner.start # usually this is called in setup of a test

dirty_the_db

DatabaseCleaner.clean # cleanup of the test

# OR

DatabaseCleaner.cleaning do
  dirty_the_db
end

At times you may want to do a single clean with one strategy.

For example, you may want to start the process by truncating all the tables, but then use the faster transaction strategy the remaining time. To accomplish this you can say:

require 'database_cleaner/active_record'

DatabaseCleaner.clean_with :truncation

DatabaseCleaner.strategy = :transaction

# then make the DatabaseCleaner.start and DatabaseCleaner.clean calls appropriately

What strategy is fastest?

For the SQL libraries the fastest option will be to use :transaction as transactions are simply rolled back. If you can use this strategy you should. However, if you wind up needing to use multiple database connections in your tests (i.e. your tests run in a different process than your application) then using this strategy becomes a bit more difficult. You can get around the problem a number of ways.

One common approach is to force all processes to use the same database connection (common ActiveRecord hack) however this approach has been reported to result in non-deterministic failures.

Another approach is to have the transactions rolled back in the application's process and relax the isolation level of the database (so the tests can read the uncommitted transactions).

An easier, but slower, solution is to use the :truncation or :deletion strategy.

So what is fastest out of :deletion and :truncation? Well, it depends on your table structure and what percentage of tables you populate in an average test. The reasoning is out of the scope of this README but here is a good SO answer on this topic for Postgres.

Some people report much faster speeds with :deletion while others say :truncation is faster for them. The best approach therefore is it try all options on your test suite and see what is faster.

If you are using ActiveRecord then take a look at the additional options available for :truncation.

Database Cleaner also includes a null strategy (that does no cleaning at all) which can be used with any ORM library. You can also explicitly use it by setting your strategy to nil.

Test Framework Examples

RSpec Example

RSpec.configure do |config|

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

  config.around(:each) do |example|
    DatabaseCleaner.cleaning do
      example.run
    end
  end

end

RSpec with Capybara Example

You'll typically discover a feature spec is incorrectly using transaction instead of truncation strategy when the data created in the spec is not visible in the app-under-test.

A frequently occurring example of this is when, after creating a user in a spec, the spec mysteriously fails to login with the user. This happens because the user is created inside of an uncommitted transaction on one database connection, while the login attempt is made using a separate database connection. This separate database connection cannot access the uncommitted user data created over the first database connection due to transaction isolation.

For feature specs using a Capybara driver for an external JavaScript-capable browser (in practice this is all drivers except :rack_test), the Rack app under test and the specs do not share a database connection.

When a spec and app-under-test do not share a database connection, you'll likely need to use the truncation strategy instead of the transaction strategy.

See the suggested config below to temporarily enable truncation strategy for affected feature specs only. This config continues to use transaction strategy for all other specs.

It's also recommended to use append_after to ensure DatabaseCleaner.clean runs after the after-test cleanup capybara/rspec installs.

require 'capybara/rspec'

#...

RSpec.configure do |config|

  config.use_transactional_fixtures = false

  config.before(:suite) do
    if config.use_transactional_fixtures?
      raise(<<-MSG)
        Delete line `config.use_transactional_fixtures = true` from rails_helper.rb
        (or set it to false) to prevent uncommitted transactions being used in
        JavaScript-dependent specs.

        During testing, the app-under-test that the browser driver connects to
        uses a different database connection to the database connection used by
        the spec. The app's database connection would not be able to access
        uncommitted transaction data setup over the spec's database connection.
      MSG
    end
    DatabaseCleaner.clean_with(:truncation)
  end

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

  config.before(:each, type: :feature) do
    # :rack_test driver's Rack app under test shares database connection
    # with the specs, so continue to use transaction strategy for speed.
    driver_shares_db_connection_with_specs = Capybara.current_driver == :rack_test

    unless driver_shares_db_connection_with_specs
      # Driver is probably for an external browser with an app
      # under test that does *not* share a database connection with the
      # specs, so use truncation strategy.
      DatabaseCleaner.strategy = :truncation
    end
  end

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

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

end

Minitest Example

DatabaseCleaner.strategy = :transaction

class Minitest::Spec
  before :each do
    DatabaseCleaner.start
  end

  after :each do
    DatabaseCleaner.clean
  end
end

# with the minitest-around gem, this may be used instead:
class Minitest::Spec
  around do |tests|
    DatabaseCleaner.cleaning(&tests)
  end
end

Cucumber Example

If you're using Cucumber with Rails, just use the generator that ships with cucumber-rails, and that will create all the code you need to integrate DatabaseCleaner into your Rails project.

Otherwise, to add DatabaseCleaner to your project by hand, create a file features/support/database_cleaner.rb that looks like this:

require 'database_cleaner/active_record'

DatabaseCleaner.strategy = :truncation

Around do |scenario, block|
  DatabaseCleaner.cleaning(&block)
end

This should cover the basics of tear down between scenarios and keeping your database clean.

For more examples see the section "Why?".

How to use with multiple ORMs

Sometimes you need to use multiple ORMs in your application.

You can use DatabaseCleaner to clean multiple ORMs, and multiple databases for those ORMs.

require 'database_cleaner/active_record'
require 'database_cleaner/mongo_mapper'

# How to specify particular orms
DatabaseCleaner[:active_record].strategy = :transaction
DatabaseCleaner[:mongo_mapper].strategy = :truncation

# How to specify particular databases
DatabaseCleaner[:active_record, db: :two]

# You may also pass in the model directly:
DatabaseCleaner[:active_record, db: ModelWithDifferentConnection]

Usage beyond that remains the same with DatabaseCleaner.start calling any setup on the different configured databases, and DatabaseCleaner.clean executing afterwards.

Why?

One of my motivations for writing this library was to have an easy way to turn on what Rails calls "transactional_fixtures" in my non-rails ActiveRecord projects.

After copying and pasting code to do this several times I decided to package it up as a gem and save everyone a bit of time.

Safeguards

DatabaseCleaner comes with safeguards against:

  • Running in production (checking for ENV, APP_ENV, RACK_ENV, and RAILS_ENV)
  • Running against a remote database (checking for a DATABASE_URL that does not include localhost, .local or 127.0.0.1)

Both safeguards can be disabled separately as follows.

Using environment variables:

export DATABASE_CLEANER_ALLOW_PRODUCTION=true
export DATABASE_CLEANER_ALLOW_REMOTE_DATABASE_URL=true

In Ruby:

DatabaseCleaner.allow_production = true
DatabaseCleaner.allow_remote_database_url = true

In Ruby, a URL allowlist can be specified. When specified, DatabaseCleaner will only allow DATABASE_URL to be equal to one of the values specified in the url allowlist like so:

DatabaseCleaner.url_allowlist = ['postgres://postgres@localhost', 'postgres://foo@bar']

Allowlist elements are matched with case equality (===), so regular expressions or procs may be used:

DatabaseCleaner.url_allowlist = [
  %r{^postgres://postgres@localhost},         # match any db with this prefix
  proc {|uri| URI.parse(uri).user == "test" } # match any db authenticating with the 'test' user
]

CHANGELOG

See HISTORY for details.

COPYRIGHT

See LICENSE for details.

database_cleaner's People

Contributors

andreale avatar benclewis avatar betelgeuse avatar bmabey avatar botandrose avatar botandrose-machine avatar bpo avatar buehmann avatar cyberdelia avatar dpisarewski avatar etagwerker avatar ethco avatar hank-spokeo avatar japgolly avatar jhollinger avatar jnv avatar johnf avatar jonrowe avatar netskin-ci avatar nyarly avatar petergoldstein avatar rhunter avatar sanemat avatar sirkosi avatar skalee avatar snusnu avatar stanislaw avatar svenfuchs avatar tommeier avatar vrinek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

database_cleaner's Issues

MongoMapper Truncation not respecting :only option

I was just taking a closer look at the MongoMapper truncation strategy and it doesn't seem to heed any of the options passed to it. So instead of just truncating the collections specified in the :only option it drops all the collections.

Need to fix that, and maybe add a good way of testing all of this as well.

Support multiple connections for a given ORM

This is very similar to the concept of having multiple ORM's in a single process:

http://github.com/bmabey/database_cleaner/issues#issue/7

Often times AR project, for example, will connect to a number of DBs. Right now all of the ORM's operate on a single DB connection. John Rowe has a fork that added support for multiple AR connections:

http://github.com/JonRowe/database_cleaner

I think since we already want to add multiple strategies for different ORMs it makes since to add a new strategy for each DB connection as well. That way you can choose to use different strategies on your different DB connections. Following the proposed API in the other issue I'm thinking of an API that would look something like:

DatabaseCleaner[:active_record, :connection => :main_db_test].clean_with :truncation
DatabaseCleaner[:active_record, :connection => :user_db_test].clean_with :truncation

If no connection is specified then the connection found on AR::Base is the only sensible default.

Assuming multiple ORM support is already added then this should be a simple addition. Strategies will now have a connection injected as opposed to relying on the ORM constant providing one (i.e. AR::Base.connection). Then the strategy will simply be added onto an array managed by DC.

I haven't put too much thought into the API so this is subject to change and suggestions/comments are very welcome.

PostgreSQL CASCADE option only available in V 8.2 and later.

When using DatabaseCleaner in a Rails-2.5 project that uses PG-8.1 DBMS I get this error:

  PGError: ERROR:  syntax error at or near "CASCADE"
  LINE 1: TRUNCATE TABLE "clearances" CASCADE;
                                      ^
  : TRUNCATE TABLE "clearances" CASCADE;

(ActiveRecord::StatementInvalid)
/usr/lib64/ruby/gems/1.8/gems/activerecord-2.3.5/lib/
active_record/connection_adapters/abstract_adapter.rb:219:in `log'

And, if I try an remove the reference to DBC from env.rb then I get
this error:
uninitialized constant DatabaseCleaner (NameError)
/usr/lib64/ruby/gems/1.8/gems/activesupport-2.3.5/lib/
active_support/dependencies.rb:443:in load_missing_constant' /usr/lib64/ruby/gems/1.8/gems/activesupport-2.3.5/lib/ active_support/dependencies.rb:80:inconst_missing'
/usr/lib64/ruby/gems/1.8/gems/activesupport-2.3.5/lib/
active_support/dependencies.rb:92:in const_missing' /usr/lib64/ruby/gems/1.8/gems/cucumber-rails-0.2.4/lib/cucumber/ rails/active_record.rb:27:inAfter

Evidently, the CASCADE option was added to PG sometime in the 8.2 series. however, PG-8.1 is the supported version that ships with Red Hat EL5 and updating the DBMS to a version not distributed with the distro is not an option.

It would be useful if DBC checked the version of PG and adjusted the syntax of the TRUNCATE command to suit versions earlier than 8.2.

rails-head superclass mismatch

Hello,
since this commit: rails/rails@5766539

I get:

/Users/kain/.rvm/gems/ruby-1.9.3-preview1@audiobox/bundler/gems/database_cleaner-7f477031e9c2/lib/database_cleaner/active_record/truncation.rb:41:in `<module:ConnectionAdapters>': superclass mismatch for class Mysql2Adapter (TypeError)
from /Users/kain/.rvm/gems/ruby-1.9.3-preview1@audiobox/bundler/gems/database_cleaner-7f477031e9c2/lib/database_cleaner/active_record/truncation.rb:7:in `<module:ActiveRecord>'
from /Users/kain/.rvm/gems/ruby-1.9.3-preview1@audiobox/bundler/gems/database_cleaner-7f477031e9c2/lib/database_cleaner/active_record/truncation.rb:6:in `<top (required)>'
from /Users/kain/.rvm/gems/ruby-1.9.3-preview1@audiobox/bundler/gems/rails-92619e4f78e9/activesupport/lib/active_support/dependencies.rb:239:in `require'
from /Users/kain/.rvm/gems/ruby-1.9.3-preview1@audiobox/bundler/gems/rails-92619e4f78e9/activesupport/lib/active_support/dependencies.rb:239:in `block in require'
from /Users/kain/.rvm/gems/ruby-1.9.3-preview1@audiobox/bundler/gems/rails-92619e4f78e9/activesupport/lib/active_support/dependencies.rb:224:in `load_dependency'
from /Users/kain/.rvm/gems/ruby-1.9.3-preview1@audiobox/bundler/gems/rails-92619e4f78e9/activesupport/lib/active_support/dependencies.rb:239:in `require'
from /Users/kain/.rvm/gems/ruby-1.9.3-preview1@audiobox/bundler/gems/database_cleaner-7f477031e9c2/lib/database_cleaner/base.rb:98:in `orm_strategy'
from /Users/kain/.rvm/gems/ruby-1.9.3-preview1@audiobox/bundler/gems/database_cleaner-7f477031e9c2/lib/database_cleaner/base.rb:34:in `create_strategy'
from /Users/kain/.rvm/gems/ruby-1.9.3-preview1@audiobox/bundler/gems/database_cleaner-7f477031e9c2/lib/database_cleaner/base.rb:38:in `clean_with'
from /Users/kain/.rvm/gems/ruby-1.9.3-preview1@audiobox/bundler/gems/database_cleaner-7f477031e9c2/lib/database_cleaner/configuration.rb:62:in `block in clean_with'
from /Users/kain/.rvm/gems/ruby-1.9.3-preview1@audiobox/bundler/gems/database_cleaner-7f477031e9c2/lib/database_cleaner/configuration.rb:62:in `each'
from /Users/kain/.rvm/gems/ruby-1.9.3-preview1@audiobox/bundler/gems/database_cleaner-7f477031e9c2/lib/database_cleaner/configuration.rb:62:in `clean_with'

Specifying location of database.yml

Hi,
Is there an easy way I can configure database_cleaner to load the database.yml from a different location than the default config/database.yml ?
Would really appreciate that!
Thanks

Invalid SAVEPOINT name for PostgreSQL 9.x (possibly 8.x) - SAVEPOINT

Using version 0.6.2, and I suspect 0.6.3 (but it's not yet in Gem mirrors, and the change-log indicates you didn't change something here) there is an error with an incorrect name for a SAVEPOINT under PostgreSQL (at least, I haven't tested other adapters)

 PGError: ERROR:  syntax error at or near "-"
       LINE 1: SAVEPOINT active_record_-529
                                       ^
       : SAVEPOINT active_record_-529

โ€ฆ hack thatโ€ฆ I'll leave this issue here, but it's not a database cleaner issueโ€ฆ the SAVEPOINT name is taken from the PostgresAdapter in ActiveRecordโ€ฆ which uses an open_transactions variable which appears (at least) to contain a negative value on my platform for some reason.

Ben, please close this. (or I will)

order of configuration matters (but it should not)

This order works for me:

DatabaseCleaner.strategy = :truncation
DatabaseCleaner.clean_with :truncation
DatabaseCleaner.orm = 'mongoid'

But this order does not:

DatabaseCleaner.orm = 'mongoid'
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.clean_with :truncation

Since these are declarative configuration statements, it would be better if the order does not matter.

How to override the after(:each) not to clean the database?

Hi, I want to clean the database just before my rspec examples run.
The default is it cleans the db after the examples run. How to configure it to clean the db just before the example run so that I can poke around the Test db to see what records were presisted?

undefined method `truncate_table' with mysql2 adapter

Hello,

looks like DBCleaner strategy :truncation doesn't work mysql2 adapter.

  DatabaseCleaner.strategy = :truncation
  DatabaseCleaner.clean
  undefined method `truncate_table' for #<ActiveRecord::ConnectionAdapters::Mysql2Adapter:0x7fcdeb8a1f68>

Error in ActiveRecord's decrement_open_transactions call, mysql and Rails 3

This is with a Rails 3.0.10 project using mysql (I'm also using mongo_mapper and redis in the same project, but not trying to use database_cleaner with them).

I upgraded from DatabaseCleaner v 0.5.2 to v 0.6.7 and now when I run tests I get a nil object error.

The error is from activerecord's "decrement_open_transactions" method here:
https://github.com/rails/rails/blob/3-0-10/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb#L175

The @open_transaction instance variable is undefined for some reason.

Is this a known issue? I downgraded to 0.5.2 and it works, so I'm going to stick with that for the time being.

My spec_helper rspec configuration block includes this:

config.use_transactional_fixtures = true

  DatabaseCleaner.strategy = :transaction

  config.before :each do
    DatabaseCleaner.start
  end

  config.after :each do
    DatabaseCleaner.clean
  end

multiple database connections do not get cleaned

hi, let's say I have two classes,

class Normal < ActiveRecord::Base
   # connection is established via regular config/database.yml settings
end

class TableInOtherDB < ActiveRecord::Base
  establish_connection :adapter => 'mysql2', :database => 'other_db', ...
end

In this case, DatabaseCleaner does not clean up the table in the other DB.

database hash fail

Trying to do this:

DatabaseCleaner[:active_record,{:connection => ActiveRecord::Base.connection}].strategy = :truncation

DatabaseCleaner[:active_record,{:connection => CoreModels::Base::Connection.connection}].strategy = :truncation, {:only => %w[users members roles sites]}

DatabaseCleaner.clean
=> ActiveRecord::StatementInvalid: PGError: ERROR:  relation "users" does not exist

But from reading the source it seems you can't pass the object pointer only a hash that is then read from database.yml :( we are using a nested database yml for multiple postgres connections so this don't work.

Would be good to pass in the connection object :)

No database specified. Missing argument: database. (ArgumentError)

Hi folks,

Getting a 'no database' error in cucumber with database cleaner that's proving very stubborn. (Goes away if I remove database cleaner.) A few things:

  • Double & triple-checked my config/database.yml file. It's legit
  • Can connect to the cucumber environment through console & interact with the db just fine
  • Using postgres for DB

If anyone has any ideas I'd be really appreciative - I'm completely stumped. Here's relevant info:

TRACE:

Exception encountered by DatabaseCleaner in Cucumber After block: No database specified. Missing argument: database.
      No database specified. Missing argument: database. (ArgumentError)
      /Users/john/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.0.rc4/lib/active_record/connection_adapters/postgresql_adapter.rb:22:in `postgresql_connection'
      /Users/john/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.0.rc4/lib/active_record/connection_adapters/abstract/connection_pool.rb:292:in `new_connection'
      /Users/john/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.0.rc4/lib/active_record/connection_adapters/abstract/connection_pool.rb:302:in `checkout_new_connection'
      /Users/john/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.0.rc4/lib/active_record/connection_adapters/abstract/connection_pool.rb:254:in `block (2 levels) in checkout'
      /Users/john/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.0.rc4/lib/active_record/connection_adapters/abstract/connection_pool.rb:250:in `loop'
      /Users/john/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.0.rc4/lib/active_record/connection_adapters/abstract/connection_pool.rb:250:in `block in checkout'
      /Users/john/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/monitor.rb:201:in `mon_synchronize'
      /Users/john/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.0.rc4/lib/active_record/connection_adapters/abstract/connection_pool.rb:249:in `checkout'
      /Users/john/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.0.rc4/lib/active_record/connection_adapters/abstract/connection_pool.rb:151:in `connection'
      /Users/john/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.0.rc4/lib/active_record/connection_adapters/abstract/connection_pool.rb:388:in `retrieve_connection'
      /Users/john/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.0.rc4/lib/active_record/connection_adapters/abstract/connection_specification.rb:107:in `retrieve_connection'
      /Users/john/.rvm/gems/ruby-1.9.2-p290/gems/cucumber-rails-1.0.2/lib/cucumber/rails/hooks/active_record.rb:7:in `connection'
      /Users/john/.rvm/gems/ruby-1.9.2-p290/gems/database_cleaner-0.6.7/lib/database_cleaner/active_record/transaction.rb:17:in `clean'
      /Users/john/.rvm/gems/ruby-1.9.2-p290/gems/database_cleaner-0.6.7/lib/database_cleaner/base.rb:77:in `clean'
      /Users/john/.rvm/gems/ruby-1.9.2-p290/gems/database_cleaner-0.6.7/lib/database_cleaner/configuration.rb:56:in `block in clean'
      /Users/john/.rvm/gems/ruby-1.9.2-p290/gems/database_cleaner-0.6.7/lib/database_cleaner/configuration.rb:56:in `each'
      /Users/john/.rvm/gems/ruby-1.9.2-p290/gems/database_cleaner-0.6.7/lib/database_cleaner/configuration.rb:56:in `clean'
      /Users/john/.rvm/gems/ruby-1.9.2-p290/gems/cucumber-rails-1.0.2/lib/cucumber/rails/hooks/database_cleaner.rb:9:in `After'

features/support/env.rb

require 'rubygems'
require 'spork'

Spork.prefork do
  require 'cucumber/rails'
  require 'database_cleaner'
  require 'database_cleaner/cucumber'


  Capybara.default_selector = :css

  ActionController::Base.allow_rescue = false

  begin
    DatabaseCleaner.strategy = :transaction
  rescue NameError
    raise "You need to add database_cleaner to your Gemfile (in the :test group) if you wish to use it."
  end

end

Spork.each_run do
  require 'factory_girl'
  require File.join(File.dirname(__FILE__), '../../lib/existing_factory/existing_factory.rb')
end

config/database.yml

default: &defaults
  adapter: postgresql
  username: rails_dev
  password: foobar

development:
  <<: *defaults
  database: fcct_d

test: &test
  <<: *defaults
  database: fcct_t

production:
  <<: *defaults
  database: fcct_p
  username: fcct
  password: k#1*5Avb3dTa

cucumber:
  adapter: postgresql
  username: rails_dev
  password: foobar
  database: fcct_t

Gemfile.lock

GEM
  remote: http://rubygems.org/
  specs:
    RedCloth (4.2.7)
    ZenTest (4.6.1)
    actionmailer (3.1.0.rc4)
      actionpack (= 3.1.0.rc4)
      mail (~> 2.3.0)
    actionpack (3.1.0.rc4)
      activemodel (= 3.1.0.rc4)
      activesupport (= 3.1.0.rc4)
      builder (~> 3.0.0)
      erubis (~> 2.7.0)
      i18n (~> 0.6)
      rack (~> 1.3.0)
      rack-cache (~> 1.0.1)
      rack-mount (~> 0.8.1)
      rack-test (~> 0.6.0)
      sprockets (~> 2.0.0.beta.10)
      tzinfo (~> 0.3.27)
    activemodel (3.1.0.rc4)
      activesupport (= 3.1.0.rc4)
      bcrypt-ruby (~> 2.1.4)
      builder (~> 3.0.0)
      i18n (~> 0.6)
    activerecord (3.1.0.rc4)
      activemodel (= 3.1.0.rc4)
      activesupport (= 3.1.0.rc4)
      arel (~> 2.1.1)
      tzinfo (~> 0.3.27)
    activeresource (3.1.0.rc4)
      activemodel (= 3.1.0.rc4)
      activesupport (= 3.1.0.rc4)
    activesupport (3.1.0.rc4)
      multi_json (~> 1.0)
    addressable (2.2.6)
    ansi (1.3.0)
    archive-tar-minitar (0.5.2)
    arel (2.1.4)
    autotest-growl (0.2.9)
    babosa (0.3.5)
    bcrypt-ruby (2.1.4)
    builder (3.0.0)
    cancan (1.6.5)
    capistrano (2.8.0)
      highline
      net-scp (>= 1.0.0)
      net-sftp (>= 2.0.0)
      net-ssh (>= 2.0.14)
      net-ssh-gateway (>= 1.1.0)
    capybara (1.0.1)
      mime-types (>= 1.16)
      nokogiri (>= 1.3.3)
      rack (>= 1.0.0)
      rack-test (>= 0.5.4)
      selenium-webdriver (~> 2.0)
      xpath (~> 0.1.4)
    childprocess (0.2.1)
      ffi (~> 1.0.6)
    coffee-script (2.2.0)
      coffee-script-source
      execjs
    coffee-script-source (1.1.2)
    columnize (0.3.4)
    cucumber (1.0.2)
      builder (>= 2.1.2)
      diff-lcs (>= 1.1.2)
      gherkin (~> 2.4.5)
      json (>= 1.4.6)
      term-ansicolor (>= 1.0.5)
    cucumber-rails (1.0.2)
      capybara (>= 1.0.0)
      cucumber (~> 1.0.0)
      nokogiri (>= 1.4.6)
    database_cleaner (0.6.7)
    devise (1.4.2)
      bcrypt-ruby (~> 2.1.2)
      orm_adapter (~> 0.0.3)
      warden (~> 1.0.3)
    diff-lcs (1.1.2)
    erubis (2.7.0)
    execjs (1.2.4)
      multi_json (~> 1.0)
    factory_girl (2.0.4)
    factory_girl_rails (1.1.0)
      factory_girl (~> 2.0.0)
      railties (>= 3.0.0)
    ffi (1.0.9)
    flutie (1.2.2)
    formtastic (1.2.4)
      actionpack (>= 2.3.7)
      activesupport (>= 2.3.7)
      i18n (~> 0.4)
    friendly_id (3.2.1.1)
      babosa (~> 0.3.0)
    fuubar (0.0.6)
      rspec (~> 2.0)
      rspec-instafail (~> 0.1.8)
      ruby-progressbar (~> 0.0.10)
    gherkin (2.4.14)
      json (>= 1.4.6)
    haml (3.1.2)
    haml-rails (0.3.4)
      actionpack (~> 3.0)
      activesupport (~> 3.0)
      haml (~> 3.0)
      railties (~> 3.0)
    highline (1.6.2)
    hike (1.2.1)
    i18n (0.6.0)
    jquery-rails (1.0.13)
      railties (~> 3.0)
      thor (~> 0.14)
    json (1.5.3)
    json_pure (1.5.3)
    launchy (2.0.5)
      addressable (~> 2.2.6)
    linecache19 (0.5.12)
      ruby_core_source (>= 0.1.4)
    mail (2.3.0)
      i18n (>= 0.4.0)
      mime-types (~> 1.16)
      treetop (~> 1.4.8)
    mime-types (1.16)
    multi_json (1.0.3)
    net-scp (1.0.4)
      net-ssh (>= 1.99.1)
    net-sftp (2.0.5)
      net-ssh (>= 2.0.9)
    net-ssh (2.2.0)
    net-ssh-gateway (1.1.0)
      net-ssh (>= 1.99.1)
    nokogiri (1.5.0)
    orm_adapter (0.0.5)
    paperclip (2.3.8)
      activerecord
      activesupport
    pg (0.11.0)
    polyglot (0.3.2)
    rack (1.3.2)
    rack-cache (1.0.2)
      rack (>= 0.4)
    rack-mount (0.8.2)
      rack (>= 1.0.0)
    rack-ssl (1.3.2)
      rack
    rack-test (0.6.1)
      rack (>= 1.0)
    rails (3.1.0.rc4)
      actionmailer (= 3.1.0.rc4)
      actionpack (= 3.1.0.rc4)
      activerecord (= 3.1.0.rc4)
      activeresource (= 3.1.0.rc4)
      activesupport (= 3.1.0.rc4)
      bundler (~> 1.0)
      railties (= 3.1.0.rc4)
    railties (3.1.0.rc4)
      actionpack (= 3.1.0.rc4)
      activesupport (= 3.1.0.rc4)
      rack-ssl (~> 1.3.2)
      rake (>= 0.8.7)
      rdoc (~> 3.4)
      thor (~> 0.14.6)
    rake (0.9.2)
    rdoc (3.9.2)
    rspec (2.6.0)
      rspec-core (~> 2.6.0)
      rspec-expectations (~> 2.6.0)
      rspec-mocks (~> 2.6.0)
    rspec-core (2.6.4)
    rspec-expectations (2.6.0)
      diff-lcs (~> 1.1.2)
    rspec-instafail (0.1.8)
    rspec-mocks (2.6.0)
    rspec-rails (2.6.1)
      actionpack (~> 3.0)
      activesupport (~> 3.0)
      railties (~> 3.0)
      rspec (~> 2.6.0)
    ruby-debug-base19 (0.11.25)
      columnize (>= 0.3.1)
      linecache19 (>= 0.5.11)
      ruby_core_source (>= 0.1.4)
    ruby-debug19 (0.11.6)
      columnize (>= 0.3.1)
      linecache19 (>= 0.5.11)
      ruby-debug-base19 (>= 0.11.19)
    ruby-progressbar (0.0.10)
    ruby_core_source (0.1.5)
      archive-tar-minitar (>= 0.5.2)
    rubyzip (0.9.4)
    sass (3.1.7)
    sass-rails (3.1.0.rc.5)
      actionpack (~> 3.1.0.rc1)
      railties (~> 3.1.0.rc1)
      sass (>= 3.1.4)
      sprockets (>= 2.0.0.beta.9)
    selenium-webdriver (2.4.0)
      childprocess (>= 0.2.1)
      ffi (>= 1.0.7)
      json_pure
      rubyzip
    shoulda (2.11.3)
    spork (0.9.0.rc9)
    sprockets (2.0.0.beta.10)
      hike (~> 1.0)
      rack (~> 1.0)
      tilt (!= 1.3.0, ~> 1.1)
    term-ansicolor (1.0.6)
    thor (0.14.6)
    tilt (1.3.2)
    treetop (1.4.10)
      polyglot
      polyglot (>= 0.3.1)
    turn (0.8.2)
      ansi (>= 1.2.2)
    tzinfo (0.3.29)
    uglifier (1.0.1)
      execjs (>= 0.3.0)
      multi_json (>= 1.0.2)
    warden (1.0.5)
      rack (>= 1.0)
    xpath (0.1.4)
      nokogiri (~> 1.3)

PLATFORMS
  ruby

DEPENDENCIES
  RedCloth (= 4.2.7)
  ZenTest
  autotest-growl
  cancan
  capistrano (= 2.8.0)
  coffee-script
  cucumber
  cucumber-rails
  database_cleaner
  devise
  factory_girl
  factory_girl_rails
  flutie
  formtastic
  friendly_id
  fuubar
  haml
  haml-rails
  jquery-rails
  launchy
  paperclip (= 2.3.8)
  pg
  rails (= 3.1.0.rc4)
  rspec
  rspec-rails
  ruby-debug19
  sass-rails (~> 3.1.0.rc)
  shoulda
  spork (= 0.9.0rc9)
  sprockets (= 2.0.0.beta.10)
  turn
  uglifier

ActiveRecord strategy now requires a config/database.yml?

Am I missing something or is using the ActiveRecord strategy without a config/database.yml (at that very location) now impossible?

I usually setup the connection manually (ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => ':memory:')) for unit tests in libraries and then set the DatabaseCleaner strategy. This now with 0.6.0 fails because I just don't have a database.yml

Database cleaner broke my rspec tests on rails 3, rspec 2, machinist and pg adapter

I run the rspec tests without database cleaner and my tests passed and work very well, but I configure the database cleaner on spec_helper.rb with config on the readme and my tests are broken.

Show me an error like this:

 Failure/Error: Unable to find matching line from backtrace
 No database specified. Missing argument: database.

I verify why its occur and check before the suite test the config load normal with all keys declared on the config/database.yml, but inside the suite before each spec the config don't load normal and load without a database name.

I using rails 3, rspec 2, machinist and pg.

Allow for specifying table truncation order

I am having to interface with an Microsoft SQL Server 2005 instance which is populated with a bunch of foreign key constraints.

The transaction strategy causes the tests to hang. I am not sure why so I went with the truncation strategy. However because database_cleaner cleans the tables in the order that it finds them it is trying to truncate tables with violates the foreign key constraints of the other tables.

Something like the following would be extremely useful

:trunctation, {:order => ['table1','table2'] }

Which would ensure that DatabaseCleaner first truncates table1 then table2 then the rest (apart from those specified by :except of course).

Doesn't work with SqlServer databases that use schemas

I'm basing this on the behavior I'm seeing, please direct me in the right direction if I've misinterpreted what's happening.

I'm using database_cleaner with cucumber, active_record, and activerecord-sqlserver-adapter.

I have a table in my database called Contact.ContactEmail. Database cleaner is trying to execute the command TRUNCATE TABLE [ContactEmail]; which fails because that table doesn't exist in the dbo schema.

Thanks,
Kevin

multiple DB support leads to undefined method

I have in my cuke env.rb...

DatabaseCleaner[:active_record, {:connection => :test}].strategy = :truncation
DatabaseCleaner[:active_record, {:connection => :test_security}].strategy = :truncation

but every time I try to run cucumber it does...

undefined method `[]' for DatabaseCleaner:Module (NoMethodError)
/Users/andy/gits/sdbpg/features/support/env.rb:34

unfortunate as your test cases show this type of code working, am I doing something wrong?

help with multiple db setup

can't seem to get a multiple db setup to work and I can't find any examples of doing this...

here is what I've got so far,

database.yml

test_security:
adapter: postgresql
username: psg_user_1
password:
database: db_1
pool: 5
timeout: 5000
test:
encoding: unicode
adapter: postgresql
username: psg_user_2
database: db_2
password:
branch_test:
encoding: unicode
adapter: postgresql
username: psg_user_1=2
database: db_3
password:

and in spec_helper:
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with :truncation
DatabaseCleaner[:active_record,{:connection => :branch_test}].strategy = :transaction
DatabaseCleaner[:active_record,{:connection => :branch_test}].clean_with :truncation
DatabaseCleaner[:active_record, {:connection => :test_security}].strategy = :transaction
DatabaseCleaner[:active_record, {:connection => :test_security}].clean_with :truncation
end

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

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

however, when I run specs I keep getting...

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.-
/Users/andy/.rvm/gems/ree-1.8.7-2011.03@sdbpg/gems/activerecord-2.3.11/lib/active_record/connection_adapters/abstract_adapter.rb:175:in decrement_open_transactions' /Users/andy/.rvm/gems/ree-1.8.7-2011.03@sdbpg/gems/database_cleaner-0.6.6/lib/database_cleaner/active_record/transaction.rb:20:inclean'
/Users/andy/.rvm/gems/ree-1.8.7-2011.03@sdbpg/gems/database_cleaner-0.6.6/lib/database_cleaner/base.rb:77:in clean' /Users/andy/.rvm/gems/ree-1.8.7-2011.03@sdbpg/gems/database_cleaner-0.6.6/lib/database_cleaner/configuration.rb:56:inclean'
/Users/andy/.rvm/gems/ree-1.8.7-2011.03@sdbpg/gems/database_cleaner-0.6.6/lib/database_cleaner/configuration.rb:56:in each' /Users/andy/.rvm/gems/ree-1.8.7-2011.03@sdbpg/gems/database_cleaner-0.6.6/lib/database_cleaner/configuration.rb:56:inclean'
/Users/andy/gits/sdbpg/spec/spec_helper.rb:42:


where line 42 corresponds to the "DatabaseCleaner.clean" line

when I comment out the other connection then it appears to not clear data

any help is much appreciated

Specifying a strategy via the multi-orm way results in a nil strategy for the autodetected one

When configured like this:

DatabaseCleaner.orm = "mongoid"

RSpec.configure do |config|
  config.before(:suite) do
   DatabaseCleaner[:mongoid].strategy = :truncation
   DatabaseCleaner.clean_with(:truncation)
 end

The following error is raised:

Please set a strategy with DatabaseCleaner.strategy=.

That is because the connections look like this:

(rdb:1) self.connections
[#<DatabaseCleaner::Base:0x105025638 @orm=:mongoid, @autodetected=true>,
 #<DatabaseCleaner::Base:0x104fe0628 @orm=:mongoid, @strategy=#<DatabaseCleaner::Mongoid::Truncation:0x104fc0788 @only=nil, @tables_to_exclude=[], @db=:default>>]

New Strategy: The Snapshot

I'd like to be able to use transactions inside my tests, so that rules out the transaction strategy.

My general pattern when running tests:

  1. Remove all the data from the database
  2. Load some initial data using factories
  3. Run tests, reverting back to the initial data after each test run

I would use the deletion or truncate pattern (fwiw, deletion is much faster than truncate for me with postgresql), but they don't revert the data to the initial state -- they erase everything. Which means I need to re-run the factories each time, which is really slow.

How the snapshot pattern should work:

  1. Remove all the data from the database
  2. Load some initial data using factories
  3. Save a dump of the database to a temp file (probably just the data, not the schema)
  4. After each test run:
  • Remove all the data from the database using the deletion strategy
  • Using raw sql, load the data dump back into the database

This would let me use transactions in tests and quickly revert to a good initial state. It probably wouldn't be as fast as the transaction pattern, but I think that would be impossible to achieve, until postgresql lets us roll back to an earlier transaction.

0.6.0 and 0.6.0.rc3 not work for mongoid, undefined method `const_get' for nil:NilClass (NoMethodError)

/Users/stone/.rvm/gems/ree-1.8.7-2010.02/gems/activesupport-3.0.1/lib/active_support/whiny_nil.rb:48:in method_missing': undefined methodconst_get' for nil:NilClass (NoMethodError)
from /Users/stone/.rvm/gems/ree-1.8.7-2010.02/gems/database_cleaner-0.6.0/lib/database_cleaner/base.rb:104:in orm_strategy' from /Users/stone/.rvm/gems/ree-1.8.7-2010.02/gems/database_cleaner-0.6.0/lib/database_cleaner/base.rb:35:increate_strategy'
from /Users/stone/.rvm/gems/ree-1.8.7-2010.02/gems/database_cleaner-0.6.0/lib/database_cleaner/base.rb:39:in clean_with' from /Users/stone/.rvm/gems/ree-1.8.7-2010.02/gems/database_cleaner-0.6.0/lib/database_cleaner/configuration.rb:51:inclean_with'
from /Users/stone/.rvm/gems/ree-1.8.7-2010.02/gems/database_cleaner-0.6.0/lib/database_cleaner/configuration.rb:51:in each' from /Users/stone/.rvm/gems/ree-1.8.7-2010.02/gems/database_cleaner-0.6.0/lib/database_cleaner/configuration.rb:51:inclean_with'

/Users/stone/.rvm/gems/ree-1.8.7-2010.02/gems/activesupport-3.0.1/lib/active_support/whiny_nil.rb:48:in method_missing': undefined methodconst_get' for nil:NilClass (NoMethodError)
from /Users/stone/.rvm/gems/ree-1.8.7-2010.02/gems/database_cleaner-0.6.0/lib/database_cleaner/base.rb:104:in orm_strategy' from /Users/stone/.rvm/gems/ree-1.8.7-2010.02/gems/database_cleaner-0.6.0/lib/database_cleaner/base.rb:35:increate_strategy'
from /Users/stone/.rvm/gems/ree-1.8.7-2010.02/gems/database_cleaner-0.6.0/lib/database_cleaner/base.rb:39:in clean_with' from /Users/stone/.rvm/gems/ree-1.8.7-2010.02/gems/database_cleaner-0.6.0/lib/database_cleaner/configuration.rb:51:inclean_with'
from /Users/stone/.rvm/gems/ree-1.8.7-2010.02/gems/database_cleaner-0.6.0/lib/database_cleaner/configuration.rb:51:in each' from /Users/stone/.rvm/gems/ree-1.8.7-2010.02/gems/database_cleaner-0.6.0/lib/database_cleaner/configuration.rb:51:inclean_with'

I tried switching back to 0.5.2, it works.

Upload to gemcutter.org

Since github isn't serving gems anymore, it would be convenient if the gem was available on gemcutter.org. Thanks!

Issue with gemspec when using bundler and git source

When I have gem "database_cleaner", :git => 'http://github.com/bmabey/database_cleaner.git'
in my gemfile, I get:

Using database_cleaner (0.6.0.rc.1) from http://github.com/bmabey/database_cleaner.git (at master) database_cleaner at /Users/momoro/.rvm/gems/ree-1.8.7-2010.02/bundler/gems/database_cleaner-99da2e3 did not have a valid gemspec. This prevents bundler from installing bins or native extensions, but that may not affect its functionality. The validation message from Rubygems was: ["examples/config/database.yml", "examples/db/activerecord_one.db", "examples/db/activerecord_two.db", "examples/db/datamapper_default.db", "examples/db/datamapper_one.db", "examples/db/datamapper_two.db"] are not files

Support multiple ORMs in a single process

I had a discussion with jerryvos over github about adding this feature. I'd like to see this added since I think more and more projects will be have multiple DBs (i.e. AR, and MongoDB). Here are some of the ideas taken from that thread:

Sorry, but currently there is no support for multiple ORM types. Once I merged in the MongoMapper support I realized that this might be a desired feature. I have thought about it a little and had similar ideas as the ones you suggested.

I like your idea of having a config for each ORM. (Whether that be an array of hashes or simple a hash keyed by the ORM.)

Perhaps when ORMs.size > 1 we could raise an error for the base commands and tell them they have to be more specific. If we don't have the base commands act on all of them then I think I would prefer to force people to be more explicit rather than just choosing ActiveRecord. So when both MongoMapper and ActiveRecord are detected:

DatabaseCleaner.clean_with :truncation # raise AmbiguousORMStrategy error or something
# a similar error would be raised for any base command like DatabaseCleaner.strategy=

The error would inform the user to use one of the following commands:

# Explicitly list them separably:
DatabaseCleaner[:mongo_mapper].clean_with :truncation
DatabaseCleaner[:active_record].clean_with :truncation

# Or explicitly point out that all will be acted on:
DatabaseCleaner[:all].clean_with :truncation  # So, have the :all shortcut...

I think forcing people to disambiguate which ORM they are acting on would prevent confusion in the future.

I like this approach this it would leave the API unchanged for the common use case of having one ORM per project. Implementation wise I think all this would entail is that the detection logic of ORM's would just stuff all of the detected ORM's into some config Hash. That way the single ORM case isn't an edge case as the configs would always live in a hash or array anyways.

Incompatibility with mysql2?

ENV: OSX, mysql 5.5.1, gem mysql2 0.2.7, database_cleaner 0.6.5

Disclaimer: I am not saying this is necessarily an issue with database_cleaner, but this error only occurs when using database_cleaner.

Using DatabaseCleaner[:active_record, {:connection => :test }].strategy = :truncation

/Users/oreoshake/.rvm/gems/ruby-1.9.2-p180/gems/activesupport-3.0.3/lib/active_support/whiny_nil.rb:48:in method_missing': undefined methodquery_options' for nil:NilClass (NoMethodError)
from /Users/oreoshake/.rvm/gems/ruby-1.9.2-p180/gems/mysql2-0.2.7/lib/active_record/connection_adapters/mysql2_adapter.rb:310:in execute' from /Users/oreoshake/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/database_statements.rb:269:inupdate_sql'
from /Users/oreoshake/.rvm/gems/ruby-1.9.2-p180/gems/mysql2-0.2.7/lib/active_record/connection_adapters/mysql2_adapter.rb:331:in update_sql' from /Users/oreoshake/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/database_statements.rb:49:inupdate'
from /Users/oreoshake/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/query_cache.rb:16:in update' from /Users/oreoshake/.rvm/gems/ruby-1.9.2-p180/gems/mysql2-0.2.7/lib/active_record/connection_adapters/mysql2_adapter.rb:237:indisable_referential_integrity'
from /Users/oreoshake/.rvm/gems/ruby-1.9.2-p180/gems/database_cleaner-0.6.5/lib/database_cleaner/active_record/truncation.rb:109:in `clean'

After digging around in the mysql2 gem, I got around this by commenting out the following lines, which apparently lead to the nil issue:

  def disconnect!
    # unless @connection.nil?
      # @connection.close
      # @connection = nil
    # end
  end

It works, but is obviously not ideal and will probably have unintended consequences. However, in my local dev environment this seems to work for the time being. I can see the truncate statements in the log, but it looks like the transaction fails during a reconnection when @connection becomes nil (even without a reconnect: true in database.yml). Commenting out the @connection = nil only does not work.

I'm not sure if this is an issue with mysql2 or database cleaner

ActiveRecord::JDBCError: ORA-00911: invalid character by DatabaseCleaner.clean

Hello,

I use database_cleaner with jruby-1.6.1, Rails 3 and Oracle.
When I use DatabaseCleaner.clean (DatabaseCleaner.strategy = :truncation) I became the following error:

  ActiveRecord::JDBCError: ORA-00911: invalid character

It happens because database_cleaner appends a ; in

lib/database_cleaner/active_record/truncation.rb

My workaround looks like this:

 class JdbcAdapter < AbstractAdapter
    def truncate_table(table_name)
        execute_with_rescue("TRUNCATE TABLE #{quote_table_name(table_name)};") ||
        execute_with_rescue("TRUNCATE TABLE #{quote_table_name(table_name)}")  ||
        execute_with_rescue("DELETE FROM #{quote_table_name(table_name)};")    ||
        execute_with_rescue("DELETE FROM #{quote_table_name(table_name)}",true)
    end

  def execute_with_rescue(stmt, exec_raise=false)
    begin
      execute(stmt)
      true
    rescue
     raise if exec_raise
     false
    end
  end
end

Regards
Dieter

fails quietly and painfully if there's a view in the database and using truncation strategy

In a database with a view, it will try to "truncate table" on the view, which throws a mysql error. At least in our setup, this fails silently in the cucumber runs, which causes random failures (data related) that are hard to diagnose. For now, we just threw a rescue after it in the gem to get our release out the door (releasing tonight), but I'm willing to work to figure out the appropriate patch here. We'll have to patch it for ourselves anyway.

Sequel ORM: Should use TRUNCATE ... CASCADE on Postgres

Surprised this isn't built into the Sequel ORM. There's no simple way to do this other than running the SQL directly.

This doesn't work:

DatabaseCleaner.clean_with(:truncation, :except => [:schema_migrations])

This does:

(DB.tables - [:schema_migrations]).each do |table|
  DB.run("TRUNCATE TABLE #{table} CASCADE;")
end

I didn't have a chance cleanly integrate this, but thought I'd at least create an issue. You could do a check to see if the db is a Sequel::Postgres::Database type prior to either running the default truncate method or running the custom SQL.

ActiveRecord/sqlite3 truncation strategy & sqlite_sequence

I'm using sqlite and ActiveRecord and the truncation strategy, and I noticed there was some funny behavior with sqlite_sequence not getting cleared. (I have some seed data with hard coded IDs, thus the problem.) I can't think of any reason why this table shouldn't be cleared, and likewise, it DOES get cleared if you use the transaction strategy. I think these two strategies should have the same effective result.

I created a small work-around for this:

earnold@98d324a

Does it seem appropriate for you?

Thanks,

Evan

SQL syntax error in DataMapper

Using git master of dm-rails and dm in a Rails 3 app along with cumber-rails (git master), I get the following error from DatabaseCleaner when I run DatabaseCleaner.clean! with the truncation strategy set.

Exception encountered: #<DataObjects::SQLError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[1]' at line 1 (code: 1064, sql state: 42000, query: SET FOREIGN_KEY_CHECKS = [1];, uri: mysql://root@localhostblockshopper-rails3_test)>

/Users/robertrouse/.rvm/gems/ruby-head@rails3/gems/database_cleaner-0.5.2/lib/database_cleaner/data_mapper/truncation.rb:32:in `disable_referential_integrity'

Line 32 is
execute("SET FOREIGN_KEY_CHECKS = #{old};")

So it looks like the select call is returning an array. So changing the line to

execute("SET FOREIGN_KEY_CHECKS = #{old.first};")

makes it run and truncate.

need a nil strategy

There should be an easy way to turn off database cleaner. LIke setting the strategy to nil.

DatabaseCleaner::Mongoid not loaded when strategy not existed

Hi,

I'm currently using the edge database_cleaner with edge cucumber-rails I've tried to run cucumber feature which defaults try to use :transaction strategy on my ORM, and it turns out that DatabaseCleaner::Mongoid doesn't get included on error.

Here is the trace log:

Using the default profile...
uninitialized constant DatabaseCleaner::Mongoid (NameError)
/Users/sikachu/.rvm/gems/ruby-1.9.2-p0@genesis/bundler/gems/database_cleaner-9bd76e743de3/lib/database_cleaner/configuration.rb:72:in `orm_module'
/Users/sikachu/.rvm/gems/ruby-1.9.2-p0@genesis/bundler/gems/database_cleaner-9bd76e743de3/lib/database_cleaner/base.rb:93:in `orm_module'
/Users/sikachu/.rvm/gems/ruby-1.9.2-p0@genesis/bundler/gems/database_cleaner-9bd76e743de3/lib/database_cleaner/base.rb:100:in `rescue in orm_strategy'
/Users/sikachu/.rvm/gems/ruby-1.9.2-p0@genesis/bundler/gems/database_cleaner-9bd76e743de3/lib/database_cleaner/base.rb:97:in `orm_strategy'
/Users/sikachu/.rvm/gems/ruby-1.9.2-p0@genesis/bundler/gems/database_cleaner-9bd76e743de3/lib/database_cleaner/base.rb:33:in `create_strategy'
/Users/sikachu/.rvm/gems/ruby-1.9.2-p0@genesis/bundler/gems/database_cleaner-9bd76e743de3/lib/database_cleaner/base.rb:47:in `strategy='
/Users/sikachu/.rvm/gems/ruby-1.9.2-p0@genesis/bundler/gems/database_cleaner-9bd76e743de3/lib/database_cleaner/configuration.rb:30:in `block in strategy='
/Users/sikachu/.rvm/gems/ruby-1.9.2-p0@genesis/bundler/gems/database_cleaner-9bd76e743de3/lib/database_cleaner/configuration.rb:30:in `each'
/Users/sikachu/.rvm/gems/ruby-1.9.2-p0@genesis/bundler/gems/database_cleaner-9bd76e743de3/lib/database_cleaner/configuration.rb:30:in `strategy='
/Users/sikachu/Projects/cucumber-rails/lib/cucumber/rails/hooks/database_cleaner.rb:5:in `<top (required)>'
/Users/sikachu/Projects/cucumber-rails/lib/cucumber/rails.rb:9:in `<top (required)>'
/Users/sikachu/Projects/genesis/features/support/env.rb:7:in `require'
/Users/sikachu/Projects/genesis/features/support/env.rb:7:in `<top (required)>'

I've dug into the source code and couldn't find the culprit. Would you mind helping me out for this? Thank you :)

PostgreSQL CASCADE error on PG vers < 8.2 and Ruby v > 1.8

The Array.to_s method has a different behaviour in Ruby V 1.9 from that of Ruby 1.8. Under 1.8 the .to_s method of Array performed an implicit .join before creating the string. Ruby 1.9 does not do this but instead produces a literal string representation of the array complete with delimiters. The difference in string representations causes the db_version check in lib/database_cleaner/active_record/truncation.rb to fail when run under Ruby 1.9.

["08.01.0009"].to_s == "08.01.0009" RUBY_VERSION = 1.8

["08.01.0009"].to_s == "["08.01.0009"]" RUBY_VERSION = 1.9

The problem is found here:

      def self.db_version
        @db_version ||= connection.select_values(
          "SELECT CHARACTER_VALUE
            FROM INFORMATION_SCHEMA.SQL_IMPLEMENTATION_INFO
            WHERE IMPLEMENTATION_INFO_NAME = 'DBMS VERSION' ").to_s
      end

The fix is to insert an explicit join. This will handle both 1.8 and 1.9 versions of Ruby.

      def self.db_version
        @db_version ||= connection.select_values(
          "SELECT CHARACTER_VALUE
            FROM INFORMATION_SCHEMA.SQL_IMPLEMENTATION_INFO
            WHERE IMPLEMENTATION_INFO_NAME = 'DBMS VERSION' ").join.to_s
      end

Excluding tables from the database clean

Howdy,
I've been digging through the code and found the except / only options but I don't quite understand how to use them.
I've tried Database.clean(:except => [:bar, :foo]) with no luck - my ruby-fu wasn't quite strong enough to understand what was going on in the code.

Cheers!
Thomas

superclass mismatch for class MysqlAdapter

I am getting a superclass mismatch for class MysqlAdapter (TypeError) on a Rails 2.3.5 application. It works fine with version 0.5.0, or if I remove the inheritance from AbstractAdapter in the class definition.

superclass mismatch for class MysqlAdapter (TypeError)
/usr/lib/ruby/gems/1.8/gems/database_cleaner-0.5.2/lib/database_cleaner/active_record/truncation.rb:14
/usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in gem_original_require' /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:inrequire'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:158:in require' /usr/lib/ruby/gems/1.8/gems/database_cleaner-0.5.2/lib/database_cleaner/configuration.rb:86:inorm_strategy'
/usr/lib/ruby/gems/1.8/gems/database_cleaner-0.5.2/lib/database_cleaner/configuration.rb:42:in create_strategy' /usr/lib/ruby/gems/1.8/gems/database_cleaner-0.5.2/lib/database_cleaner/configuration.rb:56:instrategy='
/home/eric/projects/camp/features/support/env.rb:55
/usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in gem_original_require' /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:inrequire'
/usr/lib/ruby/gems/1.8/gems/cucumber-0.7.1/bin/../lib/cucumber/rb_support/rb_language.rb:119:in load_code_file' /usr/lib/ruby/gems/1.8/gems/cucumber-0.7.1/bin/../lib/cucumber/step_mother.rb:84:inload_code_file'
/usr/lib/ruby/gems/1.8/gems/cucumber-0.7.1/bin/../lib/cucumber/step_mother.rb:76:in load_code_files' /usr/lib/ruby/gems/1.8/gems/cucumber-0.7.1/bin/../lib/cucumber/step_mother.rb:75:ineach'
/usr/lib/ruby/gems/1.8/gems/cucumber-0.7.1/bin/../lib/cucumber/step_mother.rb:75:in load_code_files' /usr/lib/ruby/gems/1.8/gems/cucumber-0.7.1/bin/../lib/cucumber/cli/main.rb:53:inexecute!'
/usr/lib/ruby/gems/1.8/gems/cucumber-0.7.1/bin/../lib/cucumber/cli/main.rb:25:in execute' /usr/lib/ruby/gems/1.8/gems/cucumber-0.7.1/bin/cucumber:8 /usr/bin/cucumber:19:inload'
/usr/bin/cucumber:19

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.