require 'database_cleaner'

RSpec.configure do |config|
  config.before(:suite) do
    config.use_transactional_fixtures = false
    DatabaseCleaner.clean_with(
        :truncation,
        except: %w(ar_internal_metadata)
    )
  end

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

  config.before(:each, js: true) do
    DatabaseCleaner.strategy = :truncation
  end

  config.before(:each, type: :request) do
    DatabaseCleaner.strategy = :truncation
  end

  # This block must be here, do not combine with the other `before(:each)` block.
  # This makes it so Capybara can see the database.
  config.before(:each) do
    DatabaseCleaner.start
  end

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

  config.append_after(:each) do
    DatabaseCleaner.clean
  end

  config.before(:each, type: :feature) do
    # :rack_test driver's Rack app under test shares database connection
    # with the specs, so continue to use transaction strategy for speed.
    driver_shares_db_connection_with_specs = Capybara.current_driver == :rack_test

    unless driver_shares_db_connection_with_specs
      # Driver is probably for an external browser with an app
      # under test that does *not* share a database connection with the
      # specs, so use truncation strategy.
      DatabaseCleaner.strategy = :truncation
    end
  end

  private

    def es_delete_all
      Opportunity.__elasticsearch__.refresh_index!
      Opportunity.__elasticsearch__.delete_all
    end
end
