Sunday, July 10, 2011

Custom RSpec be_square matcher for CarrierWave

It seems to me that when using CarrierWave for image uploads, particularly user avatars, it would be a pretty common thing to generate at least one square-cropped version of the image. CarrierWave ships with some nice custom matchers to test exact dimensions and such, but I found I wanted a way to just test that an image was square.

I did this using by building a custom matcher on top of the ones CarrierWave provides. If you have the conventional spec_helper.rb that requires support/**/*.rb, then you can just drop this somewhere like support/matchers/carrierwave_matchers.rb:


require 'carrierwave/test/matchers'
module CarrierWave
module Test
module Matchers
class BeSquare
def matches?(actual)
@actual = actual
image = ImageLoader.load_image(@actual.current_path)
@actual_width = image.width
@actual_height = image.height
@actual_width == @actual_height
end
def failure_message
"expected #{@actual.current_path.inspect} to be square, but it was #{@actual_width} by #{@actual_height}."
end
def negative_failure_message
"expected #{@actual.current_path.inspect} to not be square, but it was #{@actual_width} by #{@actual_height}"
end
end
def be_square
BeSquare.new
end
end
end
end


Then, you can use this like:


require 'spec_helper'
describe AvatarUploader do
include CarrierWave::Test::Matchers
before :all do
AvatarUploader.enable_processing = true
@uploader = AvatarUploader.new(@user, :avatar)
@uploader.store!(File.open(SOME_FILE_NAME))
end
after :all do
@uploader.remove!
AvatarUploader.enable_processing = false
end
describe "the main version" do
it "should be no larger than 512 by 512 pixels" do
@uploader.should be_no_larger_than(512, 512)
end
end
describe "the square version" do
it "should be square" do
@uploader.square.should be_square
end
end
end


1 comment:

Anonymous said...

Coding is one this which I want to learn and such posts always help me fulfilling my wish. Great article, thank you for sharing it with us