Skip to content

Instantly share code, notes, and snippets.

@palkan
Created March 28, 2017 21:49
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save palkan/680250e8ce52460730df78593d22d0af to your computer and use it in GitHub Desktop.
Save palkan/680250e8ce52460730df78593d22d0af to your computer and use it in GitHub Desktop.
AnyFixture: make DB fixtures from blocks
module AnyFixture
INSERT_RXP = /^INSERT INTO ([\S]+)/
class Cache
attr_reader :store
delegate :clear, to: :store
def initialize
@store = {}
end
def fetch(key)
return store[key] if store.key?(key)
return unless block_given?
store[key] = yield
end
end
class << self
def add(id)
cache.fetch(id) do
ActiveSupport::Notifications.subscribed(method(:subscriber), "sql.active_record") do
yield
end
end
end
def subscriber(_event, _start, _finish, _id, data)
matches = data.fetch(:sql).match(INSERT_RXP)
tables_cache[matches[1]] = true if matches
end
def clean
tables_cache.keys.each do |table|
ActiveRecord::Base.connection.execute %(
DELETE FROM #{table}
)
end
tables_cache.clear
cache.clear
end
private
def cache
@cache ||= Cache.new
end
def tables_cache
@tables_cache ||= {}
end
end
end
RSpec.configure do |config|
after(:suite) { AnyFixture.clean }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment