Database Cleaner not working in minitest rails

后端 未结 5 645
慢半拍i
慢半拍i 2021-01-02 14:48

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 valid

5条回答
  •  天涯浪人
    2021-01-02 15:04

    Short answer:

    gem install "minitest-around"
    

    Long answer:

    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.

    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
    

    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
    

    And in your test files:

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

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

提交回复
热议问题