Skip to content

Instantly share code, notes, and snippets.

@techbelly
Created June 26, 2012 14:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techbelly/2996109 to your computer and use it in GitHub Desktop.
Save techbelly/2996109 to your computer and use it in GitHub Desktop.
Quick tool for CSS Refactoring - diffs screenshots against a reference
require 'capybara'
require 'capybara/dsl'
require 'capybara/poltergeist'
require 'chunky_png'
require 'tempfile'
Capybara.run_server = false
Capybara.default_driver = :poltergeist
Capybara.javascript_driver = :poltergeist
class Screenshot < Struct.new(:reference_file,:host,:path)
include Capybara::DSL
SUCCESS, FAILURE = 0,1
def screenshot
@screenshot ||= begin
Capybara.app_host = self.host
visit(self.path);
image_name = '/tmp/ss.png'
page.driver.render(image_name,:full => true)
image_name
end
end
def checksum_match?(file1, file2)
ref_md5 = `md5 #{file1}`
new_md5 = `md5 #{file2}`
ref_md5 == new_md5
end
def reference_image
@reference_image ||= ChunkyPNG::Image.from_file(self.reference_file)
end
def new_image
@new_image ||= ChunkyPNG::Image.from_file(screenshot)
end
def highlight_diffs(new_image,diff)
x, y = diff.map{ |xy| xy[0] }, diff.map{ |xy| xy[1] }
new_image.rect(x.min, y.min, x.max, y.max, ChunkyPNG::Color.rgb(255,0,0))
diff_path = '/tmp/diff.png'
new_image.save(diff_path)
`open #{diff_path}`
end
def compare
return SUCCESS if checksum_match?(self.reference_file,screenshot)
diff = []
reference_image.height.times do |y|
reference_image.row(y).each_with_index do |pixel, x|
diff << [x,y] unless pixel == new_image[x,y]
end
end
return SUCCESS if diff.length == 0
highlight_diffs(new_image,diff)
return FAILURE
end
end
exit Screenshot.new('reference.png','http://localhost:9393','/report/aOM5U7').compare
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment