Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add repair_helper.rb file I forgot in previous commit 8a92cd
- Loading branch information
Showing
1 changed file
with
50 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
module ActiveRecord | ||
module Testing | ||
module RepairHelper | ||
def self.included(base) | ||
base.class_eval do | ||
extend ClassMethods | ||
end | ||
end | ||
|
||
module Toolbox | ||
def self.record_validations(*model_classes) | ||
model_classes.inject({}) do |repair, klass| | ||
repair[klass] ||= {} | ||
[:validate, :validate_on_create, :validate_on_update].each do |callback| | ||
the_callback = klass.instance_variable_get("@#{callback.to_s}_callbacks") | ||
repair[klass][callback] = (the_callback.nil? ? nil : the_callback.dup) | ||
end | ||
repair | ||
end | ||
end | ||
|
||
def self.reset_validations(recorded) | ||
recorded.each do |klass, repairs| | ||
[:validate, :validate_on_create, :validate_on_update].each do |callback| | ||
klass.instance_variable_set("@#{callback.to_s}_callbacks", repairs[callback]) | ||
end | ||
end | ||
end | ||
end | ||
|
||
module ClassMethods | ||
def repair_validations(*model_classes) | ||
setup do | ||
@validation_repairs = ActiveRecord::Testing::RepairHelper::Toolbox.record_validations(*model_classes) | ||
end | ||
teardown do | ||
ActiveRecord::Testing::RepairHelper::Toolbox.reset_validations(@validation_repairs) | ||
end | ||
end | ||
end | ||
|
||
def repair_validations(*model_classes, &block) | ||
validation_repairs = ActiveRecord::Testing::RepairHelper::Toolbox.record_validations(*model_classes) | ||
return block.call | ||
ensure | ||
ActiveRecord::Testing::RepairHelper::Toolbox.reset_validations(validation_repairs) | ||
end | ||
end | ||
end | ||
end |