Merge pull request #22395 from avokhmin/becomes-errors-base-2

`ActiveRecord::Base#becomes` should copy the errors
This commit is contained in:
Sean Griffin 2015-12-14 09:53:16 -07:00
commit 8d672a5f92
4 changed files with 43 additions and 2 deletions

@ -81,6 +81,18 @@ def initialize_dup(other) # :nodoc:
super
end
# Copies the errors from <tt>other</tt>.
#
# other - The ActiveModel::Errors instance.
#
# Examples
#
# person.errors.copy!(other)
def copy!(other) # :nodoc:
@messages = other.messages.dup
@details = other.details.dup
end
# Clear the error messages.
#
# person.errors.full_messages # => ["name cannot be nil"]

@ -410,4 +410,14 @@ def test_no_key
person.errors.clear
assert person.errors.details.empty?
end
test "copy errors" do
errors = ActiveModel::Errors.new(Person.new)
errors.add(:name, :invalid)
person = Person.new
person.errors.copy!(errors)
assert_equal [:name], person.errors.messages.keys
assert_equal [:name], person.errors.details.keys
end
end

@ -215,7 +215,7 @@ def becomes(klass)
became.instance_variable_set("@changed_attributes", attributes_changed_by_setter)
became.instance_variable_set("@new_record", new_record?)
became.instance_variable_set("@destroyed", destroyed?)
became.instance_variable_set("@errors", errors)
became.errors.copy!(errors)
became
end

@ -19,6 +19,8 @@
require 'models/pet'
require 'models/ship'
require 'models/toy'
require 'models/admin'
require 'models/admin/user'
require 'rexml/document'
class PersistenceTest < ActiveRecord::TestCase
@ -161,7 +163,24 @@ def test_becomes_includes_errors
assert !company.valid?
original_errors = company.errors
client = company.becomes(Client)
assert_equal original_errors, client.errors
assert_equal original_errors.keys, client.errors.keys
end
def test_becomes_errors_base
child_class = Class.new(Admin::User) do
store_accessor :settings, :foo
def self.name; 'Admin::ChildUser'; end
end
admin = Admin::User.new
admin.errors.add :token, :invalid
child = admin.becomes(child_class)
assert_equal [:token], child.errors.keys
assert_nothing_raised do
child.errors.add :foo, :invalid
end
end
def test_dupd_becomes_persists_changes_from_the_original