SQLite3::SQLException when using database_cleaner with Rails / Spork / RSpec
Asked Answered
T

2

7

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
Tartary answered 31/8, 2012 at 18:39 Comment(1)
I'm getting the same error while creating a record, may be you can help? #14367896Obeah
T
6

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
Tartary answered 31/8, 2012 at 18:39 Comment(0)
G
9

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.

Good answered 3/6, 2013 at 20:44 Comment(2)
Been a while since I had this issue. I think I may have tried that. Forget which project, so I can't re-test =\Tartary
@Tartary I thought that may have happened, but I answered to keep a record for future readers.Good
T
6

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
Tartary answered 31/8, 2012 at 18:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.