-
-
Save zoras/c9ae0f9493de68503b56e193eb3f0bf0 to your computer and use it in GitHub Desktop.
AnyFixture: make DB fixtures from blocks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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