Clear database after testing a rake task using RSpec

factory-bot, rspec, ruby, ruby-on-rails

Solution

Have you tried using `database_cleaner` gem?

You can check the great article by Avdi Grimm about how to configure it.

config.use_transactional_fixtures = false

In file `spec/support/database_cleaner.rb`:

RSpec.configure do |config|
  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end

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

  config.before(:each, :js => true) do
    DatabaseCleaner.strategy = :truncation
  end

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

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

Problem

I'm trying to test my rake task using rspec and it runs fine, but the problem is that the records aren't being deleted afterwards. I've put `config.use_transactional_fixtures = true` in the config file to no affect. In other tests it's was working fine. Here's my code: ``` require 'rspec' require 'spec_helper' require 'rake' describe 'my_app rake tasks' do describe 'rake_task_1' do before { MyApp::Application.load_tasks } it 'should test it!' do 10.times { create(:record) } Rake::Task["rake_task_1"].invoke Record.count.should == 10 end end end ``` In my rake task I'm executing a query using `ActiveRecord::Base.connection.execute`. I'm sure it has something with SQL transitions in RSepc.... any ideas?

Original source