Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite3::SQLException when using database_cleaner with Rails / Spork / RSpec

When attempting to follow example on database_cleaner's GitHub page, I encountered the following error from RSpec:

 ActiveRecord::StatementInvalid:
   SQLite3::SQLException: cannot start a transaction within a transaction: begin transaction

The configuration used in spec_helper.rb is:

require 'spork'
require 'database_cleaner'

Spork.prefork do
 # .. snip
  RSpec.configure do |config|
   # .. snip
    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
  end
end

Spork.each_run do

end
like image 642
Dan Avatar asked Aug 31 '12 18:08

Dan


2 Answers

The accepted answer makes all tests slower (when it's not needed) by truncating after each one.

Just add

config.use_transactional_fixtures = false

when using database_cleaner.

If you have both config.use_transactional_fixtures = true and DatabaseCleaner.strategy = :transaction you're going to start a transaction inside another transaction and that's not allowed.

like image 170
Filipe Giusti Avatar answered Oct 11 '22 11:10

Filipe Giusti


I found the solution to be changing the entire strategy to :truncation. Updated spec_helper:

require 'spork'
require 'database_cleaner'

Spork.prefork do

  RSpec.configure do |config|
    config.use_transactional_fixtures = false

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

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

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

  end
end

Spork.each_run do

end
like image 43
Dan Avatar answered Oct 11 '22 11:10

Dan