使用RSpec测试rake任务后清除数据库

Guy*_*gev 3 ruby rspec ruby-on-rails factory-bot

我正在尝试使用rspec测试我的rake任务,它运行良好,但问题是以后没有删除记录。

我放入config.use_transactional_fixtures = true配置文件没有任何影响。在其他测试中,它运行良好。

这是我的代码:

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
Run Code Online (Sandbox Code Playgroud)

在我的rake任务中,我正在使用执行查询ActiveRecord::Base.connection.execute。我确定它在RSepc中具有SQL转换功能。

有任何想法吗?

bac*_*rhh 5

您是否尝试过使用database_cleanergem?

您可以查看Avdi Grimm撰写精彩文章,了解如何进行配置。

config.use_transactional_fixtures = false
Run Code Online (Sandbox Code Playgroud)

在文件中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
Run Code Online (Sandbox Code Playgroud)