Skip to content

Instantly share code, notes, and snippets.

@soulcutter
Created June 10, 2015 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save soulcutter/6b4a6c3d67a8d296ffa9 to your computer and use it in GitHub Desktop.
Save soulcutter/6b4a6c3d67a8d296ffa9 to your computer and use it in GitHub Desktop.
RSpec helper for automatically cleaning up database models
# transaction/truncation strategies won't work when you have a
# capybara feature and you must preserve what's already in the
# database
#
# Usage:
# include TrackedLet
#
# track(:foo) { User.create }
# track!(:foo) { User.create }
# specify { expect(track(User.create)).to be_persisted }
module TrackedLet
module TrackHelper
def track(key, &block)
let(key) do
instance_eval(&block).tap { |x| __test_records << x }
end
end
def track!(key, &block)
let!(key) do
instance_eval(&block).tap { |x| __test_records << x }
end
end
end
def track(value)
__test_records << value
value
end
def self.included(mod)
mod.extend TrackHelper
mod.instance_eval do
let(:__test_records) { Array.new }
after { __test_records.each(&:destroy) }
end
end
end
@soulcutter
Copy link
Author

Probably worth noting that I use DatabaseCleaner and needed to set

DatabaseCleaner.strategy = DatabaseCleaner::NullStrategy

before it ever calls DatabaseCleaner.start -- or you can just avoid ever calling DatabaseCleaner.start

@soulcutter
Copy link
Author

I would not really recommend this, despite having written it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment