Skip to content

Instantly share code, notes, and snippets.

@ryanb
Created January 31, 2018 20:25
Show Gist options
  • Save ryanb/82518a0220e1f99f508360ad840f75aa to your computer and use it in GitHub Desktop.
Save ryanb/82518a0220e1f99f508360ad840f75aa to your computer and use it in GitHub Desktop.
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