数据库清理器在 minitest rails 中不起作用 [英] Database Cleaner not working in minitest rails

查看:43
本文介绍了数据库清理器在 minitest rails 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用 rake minitest:controllers 单独运行它们,我的 Minitest 控制器测试工作正常,但是当我运行 rake minitest:all 时,我收到验证失败错误.这是因为电子邮件已经用于模型测试.我用DatabaseCleaner清理了数据库,但无法清理数据库.

My Minitest controller tests are working fine if I run them alone using rake minitest:controllers but when I run rake minitest:all then I get validation failed error. It is because email is already used in model tests. I used DatabaseCleaner to clean the database but unable to clean database.

我的数据库清理代码:

require "database_cleaner"
DatabaseCleaner.strategy = :transaction

class MiniTest::Rails::ActionController::TestCase
    include Devise::TestHelpers

    def setup
      DatabaseCleaner.start
    end

    def teardown
      DatabaseCleaner.clean
    end

推荐答案

简短回答:

gem install "minitest-around"

长答案:

minitest 中的before/after 或setup/teardown 与rspec 中的NOT 挂钩,因此在minitest 中不能有多个before/after 或setup/teardown,因为它们所做的只是重新定义方法.

before/after or setup/teardown in minitest are NOT hooks as in rspec, therefore you can't have multiple before/after or setup/teardown in minitest, since what they do is just redefining the method.

为了解决这个问题,您可以使用minitest-around,它增加了对多个before/aftersetup/teardownaround,只需将 gem 添加到您的测试组:

To solve this issue, you can use minitest-around, which adds support for multiple before/after or setup/teardown and around, simply add the gem to your test group:

# put in your Gemfile
gem 'minitest-around', group: :test

要设置database_cleaner,你可以随心所欲,下面是一个设置示例:

For setting up the database_cleaner, you can have it as you want, following is an example of the setup:

# tests/support/database_cleaner.rb
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)

class Minitest::Rails::ActionController::TestCase
  def setup
    DatabaseCleaner.start
  end

  def teardown
    DatabaseCleaner.clean
  end
end

在您的测试文件中:

# tests/your/test/file_test.rb
require 'support/database_cleaner'

# assertions here ...

就是这样,有关详细信息,请参阅 Github.

That's it, see the Github for detailed info.

这篇关于数据库清理器在 minitest rails 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆