Sha256: 03554456fcfb0c94e15da231ea2bb86d13de86df08b36703f383e95f4b515a89

Contents?: true

Size: 1.65 KB

Versions: 1

Compression:

Stored size: 1.65 KB

Contents

# frozen_string_literal: true
require 'cgi'
require 'json'
require 'validated_object'
require 'web_test/util'

#
# Runs PageSpeed on a URL.
# See https://developers.google.com/speed/docs/insights/v2/reference/pagespeedapi/runpagespeed#response
#
module WebTest
  module BeFast

    class TestResult < ValidatedObject::Base
      attr_accessor :success, :score, :response
      alias success? success

      validates :success,  inclusion: [true, false]
      validates :score,    inclusion: 0..100
      validates :response, type: Hash
    end


    def self.test(url:)
      response = page_speed(url: url)

      TestResult.new do |r|
        r.score    = response.fetch(:score)
        r.success  = r.score >= 85
        r.response = response
      end
    end

    def self.page_speed(url:)
      url_param = CGI.escape(WebTest::Util.make_url(url))
      key       = ENV['WEBSERVICE_MATCHER_INSIGHTS_KEY']
      if key.nil?
        raise 'be_fast requires the WEBSERVICE_MATCHER_INSIGHTS_KEY '\
              'environment variable to be set to a Google PageSpeed '\
              'Insights API key.'
      end
      endpoint  = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed'
      api_url   = "#{endpoint}?url=#{url_param}&screenshot=false&key=#{key}"
      parse json: Faraday.get(api_url).body
    end

    def self.parse(json:)
      raw_response = JSON.parse(json)
      unless raw_response.key?('ruleGroups')
        raise "Couldn't parse the PageSpeed raw_response: #{raw_response.inspect}"
      end
      score = raw_response.fetch('ruleGroups').fetch('SPEED').fetch('score')
      {
        score: score,
        raw_response: raw_response
      }
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rspec-webservice_matchers-4.11.0 lib/web_test/be_fast.rb