Testing CSS @imports

I previously wrote a script to check files that are @imported exist in CSS stylesheets. I've turned that into a set of examples for our RSpec-based test suite. Fire the code into something like spec/views/stylesheets/import_spec.rb.

require File.dirname(__FILE__) + '/../../spec_helper'

describe "Stylesheet" do
  stylesheet_root = File.expand_path(RAILS_ROOT + '/public')
  stylesheets = Dir[File.join(stylesheet_root, "**", "*.css")]

  stylesheets.each do |stylesheet|
    describe stylesheet do
      it "should not @import files that don't exist" do

        missing_imports = []
        imports = File.read(stylesheet).split(/\n|\r/).grep(/\@import url\((.*)\)/)
        imports.each do |import|
          desired_path = import.scan(/url\((["'\ ])?(.*)\1\)/).to_a.first.to_a.last
          desired_root = desired_path[0,1] == "/" ? stylesheet_root : File.dirname(stylesheet)
          filesystem_path = File.expand_path(File.join(desired_root, desired_path))
          if !File.exists?(filesystem_path)
            missing_imports << { :path => filesystem_path, :directive => import }
          end
        end

        if missing_imports.any?
          exception = []
          missing_imports.each do |import|
            exception << "Missing @import file (#{import[:path]}) required for #{import[:directive]}"
          end
          raise exception.join("\n")
        end
      end
    end
  end
end

Leave feedback...

Commenting is closed for this article.

About the boy

A picture of Craig in grayscale

Craig Webster is a software engineer living in London. He usually works with Ruby although sometimes he sneaks in some Erlang or JavaScript. He's into rock climbing, snowboarding, skating, photography and fencing. Yes, this does mean he has a sword.

Near here you'll find Craig's homepage, contact details, PGP key and keysigning policy, and talks.

Licence

The entire content of this blog is public domain. Use it however you fancy. You don't even need to attribute it to me, although it would be nice if you did. Just don't sue me and we'll all be happy.

I Work With Rails

Recommend Me

My Travels

I go places. Do you go places too? Let's meet up!.