Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 561
Okatawa Avatar asked Oct 28 '22 20:10

Okatawa


1 Answers

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.

like image 177
user1610127 Avatar answered Nov 03 '22 00:11

user1610127