module Photographer

Constants

VERSION

Attributes

max_difference[RW]

Public Class Methods

camera(&block) click to toggle source
# File lib/photographer.rb, line 21
def camera(&block)
  @camera = block
end
configure() { |self| ... } click to toggle source
# File lib/photographer.rb, line 12
def configure
  yield self
end
dir=(path) click to toggle source
# File lib/photographer.rb, line 16
def dir=(path)
  @dir = File.join path, "snaps"
  FileUtils.mkpath @dir
end
initialize() click to toggle source
# File lib/photographer.rb, line 8
def initialize
  @max_difference = 0.1
end
snap(name) click to toggle source
# File lib/photographer.rb, line 29
def snap(name)
  path = File.join @dir, name + ".png"
  unless File.exists?(path) || update?
    raise "Snap missing. Run test with PHOTOGRAPHER=update to update."
  end

  path_new = File.join @dir, name + ".new.png"
  @camera.call path_new

  if update?
    File.delete path if File.exists? path
    File.rename path_new, path
  elsif compare(path, path_new) > @max_difference
    raise "New snap too different! Run test with PHOTOGRAPHER=update to update."
  end
end
update?() click to toggle source
# File lib/photographer.rb, line 25
def update?
  ENV["PHOTOGRAPHER"] == "update"
end

Protected Class Methods

compare(path, path_new) click to toggle source
# File lib/photographer.rb, line 48
def compare(path, path_new)
  # based on http://jeffkreeftmeijer.com/2011/comparing-images-and-creating-image-diffs/
  image = ChunkyPNG::Image.from_file path
  image_new = ChunkyPNG::Image.from_file path_new

  diff_count = 0

  image.height.times do |y|
    image.row(y).each_with_index do |pixel, x|
      diff_count += 1 unless pixel == image_new[x, y]
    end
  end

  diff_count.to_f / image.pixels.length
end