javascript_fixtures_helpers.rb 2.21 KB
Newer Older
1
require 'action_dispatch/testing/test_request'
2 3 4
require 'fileutils'

module JavaScriptFixturesHelpers
5
  extend ActiveSupport::Concern
6 7
  include Gitlab::Popen

8
  extend self
9

10
  included do |base|
11 12 13 14 15 16
    base.around do |example|
      # pick an arbitrary date from the past, so tests are not time dependent
      Timecop.freeze(Time.utc(2015, 7, 3, 10)) { example.run }
    end
  end

17 18 19 20
  def fixture_root_path
    'spec/javascripts/fixtures'
  end

21 22
  # Public: Removes all fixture files from given directory
  #
23
  # directory_name - directory of the fixtures (relative to .fixture_root_path)
24 25
  #
  def clean_frontend_fixtures(directory_name)
26 27 28
    full_directory_name = File.expand_path(directory_name, fixture_root_path)
    Dir[File.expand_path('*.html.raw', full_directory_name)].each do |file_name|
      FileUtils.rm(file_name)
29 30 31 32 33
    end
  end

  # Public: Store a response object as fixture file
  #
34
  # response - string or response object to store
35
  # fixture_file_name - file name to store the fixture in (relative to .fixture_root_path)
36 37
  #
  def store_frontend_fixture(response, fixture_file_name)
38 39
    full_fixture_path = File.expand_path(fixture_file_name, fixture_root_path)
    fixture = response.respond_to?(:body) ? parse_response(response) : response
40

41 42
    FileUtils.mkdir_p(File.dirname(full_fixture_path))
    File.write(full_fixture_path, fixture)
43 44
  end

45
  def remove_repository(project)
46
    Gitlab::Shell.new.remove_repository(project.repository_storage, project.disk_path)
47 48
  end

49 50 51 52 53 54 55
  private

  # Private: Prepare a response object for use as a frontend fixture
  #
  # response - response object to prepare
  #
  def parse_response(response)
56
    fixture = response.body
57
    fixture.force_encoding("utf-8")
58 59 60 61 62

    response_mime_type = Mime::Type.lookup(response.content_type)
    if response_mime_type.html?
      doc = Nokogiri::HTML::DocumentFragment.parse(fixture)

63 64 65
      link_tags = doc.css('link')
      link_tags.remove

Phil Hughes's avatar
Phil Hughes committed
66
      scripts = doc.css("script:not([type='text/template']):not([type='text/x-template'])")
67 68 69 70 71
      scripts.remove

      fixture = doc.to_html

      # replace relative links
72 73
      test_host = ActionDispatch::TestRequest::DEFAULT_ENV['HTTP_HOST']
      fixture.gsub!(%r{="/}, "=\"http://#{test_host}/")
74 75
    end

76
    fixture
77 78
  end
end