summaryrefslogtreecommitdiff
path: root/spec/support/helpers/javascript_fixtures_helpers.rb
blob: f525b2f945ea3186b33da3dc4e3dd34e088c69e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
require 'action_dispatch/testing/test_request'
require 'fileutils'

module JavaScriptFixturesHelpers
  extend ActiveSupport::Concern
  include Gitlab::Popen

  FIXTURE_PATHS = %w[spec/javascripts/fixtures ee/spec/javascripts/fixtures].freeze

  included do |base|
    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

  # Public: Removes all fixture files from given directory
  #
  # directory_name - directory of the fixtures (relative to FIXTURE_PATHS)
  #
  def clean_frontend_fixtures(directory_name)
    FIXTURE_PATHS.each do |fixture_path|
      directory_name = File.expand_path(directory_name, fixture_path)
      Dir[File.expand_path('*.html.raw', directory_name)].each do |file_name|
        FileUtils.rm(file_name)
      end
    end
  end

  # Public: Store a response object as fixture file
  #
  # response - string or response object to store
  # fixture_file_name - file name to store the fixture in (relative to FIXTURE_PATHS)
  #
  def store_frontend_fixture(response, fixture_file_name)
    FIXTURE_PATHS.each do |fixture_path|
      fixture_file_name = File.expand_path(fixture_file_name, fixture_path)
      fixture = response.respond_to?(:body) ? parse_response(response) : response

      FileUtils.mkdir_p(File.dirname(fixture_file_name))
      File.write(fixture_file_name, fixture)
    end
  end

  def remove_repository(project)
    Gitlab::Shell.new.remove_repository(project.repository_storage, project.disk_path)
  end

  private

  # Private: Prepare a response object for use as a frontend fixture
  #
  # response - response object to prepare
  #
  def parse_response(response)
    fixture = response.body
    fixture.force_encoding("utf-8")

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

      link_tags = doc.css('link')
      link_tags.remove

      scripts = doc.css("script:not([type='text/template']):not([type='text/x-template'])")
      scripts.remove

      fixture = doc.to_html

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

    fixture
  end
end