简体   繁体   中英

Minitest and setup/teardown hooks

I have the following code in test_helper

require "minitest/spec"
require "minitest/autorun"
require "database_cleaner"

class ActiveSupport::TestCase
  DatabaseCleaner.strategy = :deletion

  include Minitest::Spec::DSL

  setup { DatabaseCleaner.start }
  teardown { DatabaseCleaner.clean }
end

And if I write such a test

class MyTest < ActiveSupport::TestCase
  test 'test' do
    #some code
  end
end

setup and teardown are executed

But if I write test like this

class MyTest < ActiveSupport::TestCase
  describe 'some test'
    before do
       @user = FactoryBot.create(:user)
    end

    it 'first test' do
      # some code
    end

    it 'second test' do
      # some code
    end
  end
end

setup and teardown are not executed. Why? Can I fix it?

Try adding the following to your test_helper.rb :

class Minitest::Spec
  before :each do
    DatabaseCleaner.start
  end

  after :each do
    DatabaseCleaner.clean
  end
end

Or, if you're using minitest-around gem:

class Minitest::Spec
  around do |tests|
    DatabaseCleaner.cleaning(&tests)
  end
end

Important here is the use Minitest::Spec class instead of ActiveSupport::TestCase .

See database cleaner docs for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM