module BetterHtml::TestHelper::SafeErbTester

Constants

SAFETY_TIPS

Public Instance Methods

assert_erb_safety(data, **options) click to toggle source
# File lib/better_html/test_helper/safe_erb_tester.rb, line 37
      def assert_erb_safety(data, **options)
        options = options.present? ? options.dup : {}
        options[:template_language] ||= :html
        buffer = ::Parser::Source::Buffer.new(options[:filename] || '(buffer)')
        buffer.source = data
        parser = BetterHtml::Parser.new(buffer, **options)

        tester_classes = [
          SafeErb::NoStatements,
          SafeErb::AllowedScriptType,
          SafeErb::NoJavascriptTagHelper,
          SafeErb::ScriptInterpolation,
        ]
        if options[:template_language] == :html
          tester_classes << SafeErb::TagInterpolation
        end

        testers = tester_classes.map do |tester_klass|
          tester_klass.new(parser)
        end
        testers.each(&:validate)
        errors = testers.map(&:errors).flatten

        messages = errors.map do |error|
          <<~EOL
          In #{buffer.name}:#{error.location.line}
          #{error.message}
          #{error.location.line_source_with_underline}\n
          EOL
        end
        messages << SAFETY_TIPS

        assert_predicate errors, :empty?, messages.join
      end