ruby-on-rails - 使用 RSpec 测试 rake 任务后清除数据库

标签 ruby-on-rails ruby rspec 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

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

有什么想法吗?

最佳答案

您是否尝试过使用 database_cleaner gem ?

您可以查看 great article by Avdi Grimm关于如何配置它。

config.use_transactional_fixtures = false

在文件 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

关于ruby-on-rails - 使用 RSpec 测试 rake 任务后清除数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22590620/

相关文章:

rspec - rspec 是否记住了 `subject` block ?

ruby-on-rails - 如何在Ruby On Rails中使用内部联接

ruby-on-rails - 序列化模型子项的 JSON 关联

ruby-on-rails - Rails + Passenger : Invalid Route name, 已在使用中

ruby-on-rails - 从 Rails Helper 返回多个标签的最佳方式是什么?

ruby - hadoop流,如何设置分区?

ruby-on-rails - 如何配置 Ransack Rails Gem 添加 NULLS LAST 进行排序

ruby-on-rails - 将反向代理添加到heroku

ruby-on-rails - cucumber 与 RSpec

ruby-on-rails - 带有 Capybara have_css 匹配器的 Rspec 不起作用