Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear database after testing a rake task using RSpec

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?

like image 990
Guy Segev Avatar asked Mar 20 '23 03:03

Guy Segev


1 Answers

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
like image 192
backpackerhh Avatar answered Apr 01 '23 07:04

backpackerhh