Created
March 3, 2020 03:33
Star
You must be signed in to star a gist
Manually your Rails test fixtures whenever you want
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
#!/usr/bin/env ruby | |
ENV["RAILS_ENV"] = "test" | |
require_relative "../config/environment" | |
ResetsFixtures.new.call |
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
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 |
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
I love to Manually My Test Fixtures! 😻