Created
March 3, 2020 03:33
-
-
Save searls/02030a3e05bf627bb0d3b94f2d36b1df to your computer and use it in GitHub Desktop.
Manually your Rails test fixtures whenever you want
This file contains hidden or 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 hidden or 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think I did something similar with db/seeds using the NamedSeeds gem (https://github.com/metaskills/named_seeds) and calling
NamedSeeds.load_seed