Skip to content

Instantly share code, notes, and snippets.

@jcartledge
Last active December 13, 2015 16:48
Show Gist options
  • Save jcartledge/4942660 to your computer and use it in GitHub Desktop.
Save jcartledge/4942660 to your computer and use it in GitHub Desktop.
Cucumber step to check that no linked stylesheets have too many selectors.

Hopefully you never have to do this, but if e.g. you build a lot of stuff on top of a library like Bootstrap and then concatenate all your CSS for shipping you might find that you hit IE<10's 4095-selectors-per-sheet limit.

To guard against this we added the following to our Cucumber tests which run in our CI build.

This works with Poltergeist which is a Capybara adapter that wraps PhantomJS.

It's arguably an abuse of Cucumber because we're definitely not testing behaviour here, but it's handy to have non-functional stuff like CSS bloat tracked in a continuous build, especially when the consequences include dropping styles on the floor.

If you're building a Rails app, skip this and use something like css_splitter to circumvent the issue.

If you concatenate CSS as a build step, not at runtime, maybe try bless.

Then /^no stylesheet should have more than (\d+) selectors$/ do |max|
js = <<-JS
(function() {
var host_re = new RegExp('^' + location.origin.replace(/([\.\/])/g, "\\$1"));
return [].filter.call(document.styleSheets, function(sheet) {
return sheet.href && sheet.href.match(host_re);
}).reduce(function(max, sheet) {
return Math.max(max, [].reduce.call(sheet.rules, function(total, rule) {
return total + ('' + rule.selectorText).split(/,/).length;
}, 0));
}, 0);
}());
JS
num_selectors = page.evaluate_script js
if num_selectors > max.to_i
raise "Too many selectors in one sheet: #{num_selectors}"
end
end
Feature: Support IE
In order to participate in the web
As an IE user
I want equal access to your website
Scenario: We should not exceed the IE selector limit
When I am on the homepage
Then no stylesheet should have more than 4095 selectors
# Obviously this is awkward - see the note about abuse of BDD above.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment