清理测试数据库,仅使用RSPEC和Capybara运行测试生成的数据

问题描述 投票:1回答:2

我在rails 4.1中有一个应用程序,我正在使用RSPEC和Capybara进行测试,因为我有一个测试数据库,其中包含用于执行测试的数据,我正在运行一个测试,生成一些存储在bd,或者我需要的是,在运行测试后,这些数据不会存储在其中。

我使用了gem database_cleaner(清理测试数据库,只有使用RSPEC和Capybara运行测试的数据),但这清除了测试bd的所有数据,我只想删除测试生成的数据。

我有这个配置,测试是一个javascript测试:

config.use_transactional_fixtures = false
    config.before(:suite) do
        if config.use_transactional_fixtures?
             raise(<<-MSG)
             Delete line `config.use_transactional_fixtures = true` from rails_helper.rb
             (or set it to false) to prevent uncommitted transactions being used in
             JavaScript-dependent specs.

             During testing, the app-under-test that the browser driver connects to
        uses a different database connection to the database connection used by
            the spec. The app's database connection would not be able to access
            uncommitted transaction data setup over the spec's database connection.
            MSG
        end
    DatabaseCleaner.clean_with(:truncation)
end

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

    config.before(:each, type: :feature) do
        driver_shares_db_connection_with_specs = Capybara.current_driver == :rack_test

        if !driver_shares_db_connection_with_specs
            DatabaseCleaner.strategy = :truncation
    end
end
ruby-on-rails ruby rspec capybara rspec-rails
2个回答
1
投票

如果您在包含要在测试中保存的数据的表中创建记录,则没有简单的方法(database_cleaner的简单配置更改等)来执行您想要的操作 - 在测试开始时维护数据。那是因为那将是database_cleaner的事务模式,它与rails 4.1中的Capybara和JS测试不兼容(在Rails 5.1中,事务模式兼容,大多数配置不再需要database_cleaner)

如果您没有在要从测试中保存的表中创建/删除/更新记录,那么您可以告诉database_cleaner跳过这些表。

既然要做你想做的事情并不容易,你应该问问自己为什么要尝试做其他人不做的事情,也许会调整你做事的方式。

如果你仍想继续你想要做的事情(并且你没有修改测试中的任何现有数据(只是添加新行),那么你需要创建一个存储最大id的before钩子在每个表中,然后是一个后挂钩,删除具有较大ID的记录,而不是使用database_cleaner


0
投票

你可以用它

rake db:reset RAILS_ENV=test
© www.soinside.com 2019 - 2024. All rights reserved.