# Based on https://stackoverflow.com/a/29544674
module DownloadHelpers
  def downloads_dir
    File.join(__dir__, 'downloads')
  end

  def wait_for_download
    sleep 1
    Timeout.timeout(Capybara.default_max_wait_time) do
      sleep 1 until downloaded?
    end
  end

  def downloaded_file
    downloads.first
  end

  def clear_downloads
    FileUtils.rm(downloads)
  end

  def downloaded?
    !downloading? && downloads.any?
  end

  def downloading?
    downloads.grep(/\.part$/).any?
  end

  def downloads
    Dir[File.join(downloads_dir, '*')]
  end
end

# Based on https://stackoverflow.com/a/29544674
module DownloadHelpers
  def downloads_dir
    File.join(__dir__, 'downloads')
  end

  def wait_for_download
    Timeout.timeout(Capybara.default_max_wait_time) do
      loop do
        sleep 1
        break if downloaded?
      end
    end
  end

  def downloaded_file
    downloads.first
  end

  def clear_downloads
    FileUtils.rm(downloads)
  end

  def downloaded?
    !downloading? && downloads.any?
  end

  def downloading?
    downloads.grep(/\.part$/).any?
  end

  def downloads
    Dir[File.join(downloads_dir, '*')]
  end
end

Use do...while instead of while in wait_for_download
Use do...while instead of while in wait_for_download

This gives browser the time to have started a new download. Also,
FileUtils.rm can take time to have effect. Even though this time
is in millisecond level, it can sometime happen that downloaded?
returns true simply because the old file hasn't been deleted yet.

Signed-off-by: Anurag Priyam <6e6ab5ea9cb59fe7c35d2a1fc74443577eb60635@gmail.com>
