Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.