Skip to content

Instantly share code, notes, and snippets.

@joshRpowell
Forked from jovanmaric/avatar_uploader.rb
Created September 20, 2022 19:52
Show Gist options
  • Save joshRpowell/924969062d113166d909c2f07c8754ff to your computer and use it in GitHub Desktop.
Save joshRpowell/924969062d113166d909c2f07c8754ff to your computer and use it in GitHub Desktop.
Testing shrine validations with RSpec
# app/uploaders/avatar_uploader.rb
class AvatarUploader < Shrine
plugin :validation_helpers
Attacher.validate do
validate_mime_type_inclusion %w[image/jpeg]
validate_max_size 10.megabytes
end
end
# spec/support/shrine.rb
# frozen_string_literal: true
require 'shrine/storage/memory'
include ActionDispatch::TestProcess
RSpec.configure do |config|
config.before(:suite) do
image = fixture_file_upload(Rails.root.join('spec', 'support',
'images',
'real_image.jpg'))
Shrine.storages[:store].upload(image, 'real_image.jpg')
end
end
# config/initializers/shrine.rb
require 'shrine'
if Rails.env.production? || Rails.env.staging?
require 'shrine/storage/s3'
require 'shrine/storage/file_system'
s3_options = {
access_key_id: ENV['AWS_ACCESS_KEY_ID'],
secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
region: ENV['AWS_REGION'],
bucket: ENV['S3_BUCKET_NAME']
}
Shrine.storages = {
cache: Shrine::Storage::FileSystem.new('tmp', prefix: 'uploads/cache'),
store: Shrine::Storage::S3.new(**s3_options)
}
Shrine.plugin :logging, logger: Rails.logger
else
require 'shrine/storage/memory'
Shrine.storages = {
cache: Shrine::Storage::Memory.new,
store: Shrine::Storage::Memory.new
}
end
Shrine.plugin :activerecord
Shrine.plugin :determine_mime_type
Shrine.plugin :cached_attachment_data
Shrine.plugin :restore_cached_data
Shrine.plugin :delete_promoted
Shrine.plugin :delete_raw
Shrine.plugin :remove_invalid
# spec/support/factories/user.rb
FactoryBot.define do
factory :user do
avatar do
Shrine.uploaded_file(
'id' => 'real_image.jpg',
'storage' => 'store',
'metadata' => { 'mime_type' => 'image/jpeg', 'size' => 100 }
)
end
end
end
# spec/models/user_spec.rb
require 'rails_helper'
RSpec.describe User, type: :model do
describe 'avatar' do
context 'with improper mime type' do
let(:faulty_avatar) do
Shrine.uploaded_file(
'id' => 'real_image.jpg',
'storage' => 'store',
'metadata' => { 'mime_type' => 'text/plain', 'size' => 11.megabytes }
)
end
before do
basic_details.update(avatar: faulty_avatar)
end
it 'is not of allowed type' do
expect(basic_details.errors[:avatar])
.to include("isn't of allowed type (allowed types: image/jpeg)")
end
it 'is not within upload limits' do
expect(basic_details.errors[:avatar])
.to include('is too large (max is 10.0 MB)')
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment