Skip to content

Instantly share code, notes, and snippets.

@searls
Created March 3, 2020 03:33
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save searls/02030a3e05bf627bb0d3b94f2d36b1df to your computer and use it in GitHub Desktop.
Manually your Rails test fixtures whenever you want
#!/usr/bin/env ruby
ENV["RAILS_ENV"] = "test"
require_relative "../config/environment"
ResetsFixtures.new.call
class ResetsFixtures
def call
raise "This only makes works in a test env!" unless Rails.env.test?
connections = gather_connections
rollback_transaction(connections)
recreate_fixtures
restart_transaction(connections)
end
private
def gather_connections
ActiveRecord::Base.connection_handler.connection_pool_list.map(&:connection)
end
def rollback_transaction(connections)
connections.each do |connection|
connection.rollback_transaction if connection.transaction_open?
connection.pool.lock_thread = false
end
end
def recreate_fixtures
require "active_record/fixtures"
ActiveRecord::FixtureSet.reset_cache
ActiveRecord::FixtureSet.create_fixtures(
"test/fixtures",
Dir["test/fixtures/*.yml"].map { |path|
path.match(/test\/fixtures\/(.*)\.yml/)[1]
}
)
end
def restart_transaction(connections)
connections.each do |connection|
connection.begin_transaction joinable: false, _lazy: false
connection.pool.lock_thread = true
end
end
end
@coreyhaines
Copy link

coreyhaines commented Mar 3, 2020

I love to Manually My Test Fixtures! 😻

@metaskills
Copy link

I think I did something similar with db/seeds using the NamedSeeds gem (https://github.com/metaskills/named_seeds) and calling NamedSeeds.load_seed

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