ksalmon
8/4/2015 - 8:36 PM

css_test.rb

feature 'Stylesheets' do
  scenario 'are all smaller than the Internet Explorer maximum' do
    stylesheets = []

    #### This will examine the HTML at the given URL and check the stylesheets
    #### linked therein. Add similar calls as needed to visit pages that expose
    #### all of your site's CSS
    stylesheets += stylesheets_at_url('/')


    stylesheets.each do |stylesheet|
      visit stylesheet
      count = count_selectors(source)

      # puts "#{stylesheet}: #{count}"

      count.should be_<(4096), "#{stylesheet} contains #{count} selectors, which exceeds Internet Explorer maximum of 4096"
    end
  end

  def stylesheets_at_url(url)
    visit url

    page.all('link[rel="stylesheet"][href]').map do |node|
      node['href']
    end
  end

  def count_selectors(css)
    css.lines("}").inject(0) { |memo, rule| memo += count_selectors_of_rule(rule) }
  end

  def count_selectors_of_rule(rule)
    rule.partition(/\{/).first.scan(/,/).count.to_i + 1
  end
end