summaryrefslogtreecommitdiff
path: root/qa/qa/page/view.rb
blob: 96f3917a8ab90d2b32999dddcd36707720787dcd (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
# frozen_string_literal: true

require 'pathname'

module QA
  module Page
    class View
      attr_reader :path, :elements

      def initialize(path, elements)
        @path = path
        @elements = elements
      end

      def pathname
        @pathname ||= ::Pathname.new(::File.join(__dir__, '../../../', @path))
          .cleanpath.expand_path
      end

      def errors
        unless pathname.readable?
          return ["Missing view partial `#{pathname}`!"]
        end

        ##
        # Reduce required elements by streaming view and making assertions on
        # elements' existence.
        #
        @missing ||= @elements.dup.tap do |elements|
          ::File.foreach(pathname.to_s) do |line|
            elements.reject! { |element| element.matches?(line) }
          end
        end

        @missing.map do |missing|
          "Missing element `#{missing.name}` in `#{pathname}` view partial!"
        end
      end

      def self.evaluate(&block)
        Page::View::DSL.new.tap do |evaluator|
          evaluator.instance_exec(&block) if block_given?
        end
      end

      class DSL
        attr_reader :elements

        def initialize
          @elements = []
        end

        def element(name, pattern = nil)
          @elements.push(Page::Element.new(name, pattern))
        end
      end
    end
  end
end