Sha256: 231c98b9fd8f066b74c69d1eacfcc78d57c7b297fef28963f03e3d895306f05a

Contents?: true

Size: 1.12 KB

Versions: 6

Compression:

Stored size: 1.12 KB

Contents

# frozen_string_literal: true

module RSpecHTML
  module Matchers
    # Matches text or regex within a given DOM element (strips HTML tags and compares text content only).
    class MatchText
      include Base

      diffable

      def match(actual)
        raise_argument_error unless actual.is_a?(RSpecHTML::Element)
        @rspec_actual = actual&.text
        return regexp_match?(actual) || regexp_siblings_match?(actual) if @expected.is_a?(Regexp)

        string_match?(actual) || string_siblings_match?(actual)
      end

      private

      def regexp_match?(actual)
        @expected.match(actual&.text || '')
      end

      def regexp_siblings_match?(actual)
        actual.siblings.any? { |sibling| @expected.match(sibling&.text || '') }
      end

      def string_match?(actual)
        (actual&.text || '').include?(@expected.to_s)
      end

      def string_siblings_match?(actual)
        actual.siblings.any? { |sibling| (sibling&.text || '').include?(@expected.to_s) }
      end

      def raise_argument_error
        raise ArgumentError, 'Expected RSpecHTML::Element with `match_text` matcher.'
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rspec-html-0.2.20 lib/rspec_html/matchers/match_text.rb
rspec-html-0.2.19 lib/rspec_html/matchers/match_text.rb
rspec-html-0.2.18 lib/rspec_html/matchers/match_text.rb
rspec-html-0.2.17 lib/rspec_html/matchers/match_text.rb
rspec-html-0.2.16 lib/rspec_html/matchers/match_text.rb
rspec-html-0.2.15 lib/rspec_html/matchers/match_text.rb