Skip to content

Instantly share code, notes, and snippets.

@iSarCasm
Last active January 3, 2016 20:36
Show Gist options
  • Save iSarCasm/9f92cb5a4ef094e1ce14 to your computer and use it in GitHub Desktop.
Save iSarCasm/9f92cb5a4ef094e1ce14 to your computer and use it in GitHub Desktop.
class ImageValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless value =~ /\.(gif|jpg|png)\Z}/i
record.errors[attribute] << (options[:message] || "is not an image")
end
end
end
class Product < ActiveRecord::Base
validates :title, :description, presence: true
validates :title, uniqueness: true
validates :price, numericality: { greater_than_or_equal_to: 0.01 }
validates :image_url, image: true
end
require 'rails_helper'
RSpec.describe Product, type: :model do
it { should validate_presence_of(:title) }
it { should validate_uniqueness_of(:title) }
it { should validate_numericality_of(:price)
.is_greater_than_or_equal_to(0.01) }
it { should validate_image_of(:image_url)}
end
require 'spec_helper'
describe "ImageValidator" do
before(:each) do
@validator = ImageValidator.new({attributes: {not_blank: true}})
@model = double('model')
allow(@model).to receive("errors").and_return([])
allow(@model.errors).to receive('[]').and_return([])
end
it "should validate valid image" do
expect(@model).not_to receive(:errors)
@validator.validate_each(@model, :image_url, "image.png")
end
it "should validate invalid image" do
expect(@model).to receive(:errors)
@validator.validate_each(@model, :image_url, "totally_an_image.csv")
end
end
RSpec::Matchers.define :validate_image_of do |attribute|
match do |actual|
validates_valid = -> {
actual.send("#{attribute}=", 'image.png')
actual.valid?
actual.errors[attribute].empty?
}.call
validates_invalid = -> {
actual.send("#{attribute}=", 'totally_an_image.csv')
actual.valid?
actual.errors[attribute].any?
}.call
validates_valid && validates_invalid
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment