Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swap between file system and in-memory storage for Shrine file uploads with RSpec.
# This sets up both a memory store and file system store for Shrine file uploads.
# We use the memory store by default but in cases where you want to test actual
# file uploads you can enable it with `file_upload: true` on a per example basis
require "shrine/storage/memory"
require "shrine/storage/file_system"
# We use a delegator to swap out the storage dynamically
# since the storage hash is duplicated for each uploader
class Shrine::Storage::Dynamic < SimpleDelegator
def initialize(initial, storages)
@_storages = storages
super(@_storages[initial])
end
def change_storage(key)
__setobj__(@_storages[key])
end
end
Shrine.storages = {
cache: Shrine::Storage::Dynamic.new(:memory,
memory: Shrine::Storage::Memory.new,
file: Shrine::Storage::FileSystem.new("public", prefix: "uploads/tmp/cache")),
store: Shrine::Storage::Dynamic.new(:memory,
memory: Shrine::Storage::Memory.new,
file: Shrine::Storage::FileSystem.new("public", prefix: "uploads/tmp/store"))
}
RSpec.configure do |config|
config.before file_upload: true do
Shrine.storages[:cache].change_storage(:file)
Shrine.storages[:store].change_storage(:file)
end
config.after file_upload: true do
Shrine.storages[:cache].change_storage(:memory)
Shrine.storages[:store].change_storage(:memory)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment