【问题标题】:how to clean database before running the each spec file?如何在运行每个规范文件之前清理数据库?
【发布时间】:2017-06-14 04:38:48
【问题描述】:

我想在运行每个规范文件之前清除我的测试数据库。

我已经在工厂女孩中使用 rspec。

谢谢, 野兔

【问题讨论】:

  • 你在使用database_cleaner gem吗?
  • 是的,我正在使用它。但不确定如何为每个文件编写。

标签: ruby-on-rails ruby rspec rspec-rails database-cleaner


【解决方案1】:

在您的 spec_helper.rb 中, 在 RSpec.configure 块内

RSpec.configure do |config|

  # ...

  config.before(:suite) do
    DatabaseCleaner.clean_with :transaction
  end

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

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

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

  # ...
end

before(:all) 和 after(:all) 对每个规范文件运行,而不是在整个套件之前和之后运行。因此,对于每个规范文件,您都可以使用以下三种策略中的任何一种来清除数据库:transaction、:truncation、:deletion

【讨论】:

  • ?这看起来就像@VAD 2017 年 1 月 28 日的回答。
  • VAD 的答案将为每个测试用例清理数据库,我的对每个规范文件都执行此操作(这是实际问题)。区别是 :all 而不是 :each
【解决方案2】:

这是我通常为 DatabaseCleaner 做的事情

# Database Cleaner
config.before(:suite) do
  DatabaseCleaner.strategy = :transaction
  DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
  DatabaseCleaner.start
end
config.after(:each) do
  DatabaseCleaner.clean
end

这将确保每次测试都有一个干净的数据库。

结帐a related, albeit old, article by Avdi 了解更多信息。

【讨论】:

    【解决方案3】:

    添加到您的spec_helper.rb 中的RSpec.configure

      config.before(:suite) do
        DatabaseCleaner.clean_with :truncation
      end
    
      config.before(:each) do
        DatabaseCleaner.strategy = :transaction
      end
    
      config.before(:each) do
        DatabaseCleaner.start
      end
    
      config.after(:each) do
        DatabaseCleaner.clean
      end
    

    必须工作

    【讨论】:

    • 实际上在我的规范/控制器文件夹中有很多控制器,我想在运行每个控制器之前清理我的数据库。
    • 在执行每个测试之前应该清理他们的数据库。有必要确保之前执行的测试不会影响为当前测试准备的测试环境,例如您的测试数据库中没有任何垃圾。
    • 为什么需要设置策略before :eachbefore :suite 还不够吗?
    • 在每次测试后清理数据库,以便下一次测试可以使用干净的数据库,而不会产生上一次测试的垃圾。这个想法是你需要在干净的设置上运行每一个测试
    猜你喜欢
    • 1970-01-01
    • 2013-04-25
    • 2014-10-19
    • 2013-12-16
    • 1970-01-01
    • 2021-09-19
    • 2010-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多