ttsvetko
9/11/2012 - 10:00 PM

An acceptance test to make sure that all CSS files contain fewer than 4096 rules

An acceptance test to make sure that all CSS files contain fewer than 4096 rules

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