Permalink
Browse files

Merge pull request #9474 from HonoreDB/master

More helpful error message when instantiating an abstract class

Conflicts:
	activerecord/CHANGELOG.md
  • Loading branch information...
2 parents cf09ac3 + 53f18f2 commit d3adfd6d3b6bb07f4e4d56b017eff1ff740523ff @rafaelfranca rafaelfranca committed Mar 7, 2013
@@ -1,5 +1,9 @@
## Rails 4.0.0 (unreleased) ##
+* Throw `NotImplementedError` when trying to instantiate `ActiveRecord::Base` or an abstract class.
+
+ *Aaron Weiner*
+
* Warn when `rake db:structure:dump` with a mysl database and
`mysqldump` is not in the PATH or fails.
Fixes #9518.
@@ -15,6 +15,9 @@ module ClassMethods
# and if the inheritance column is attr accessible, it initializes an
# instance of the given subclass instead of the base class
def new(*args, &block)
+ if abstract_class? || self == Base
+ raise NotImplementedError, "#{self} is an abstract class and can not be instantiated."
+ end
if (attrs = args.first).is_a?(Hash)
if subclass = subclass_from_attrs(attrs)
return subclass.new(*args, &block)
@@ -307,6 +307,20 @@ def test_initialize_with_invalid_attribute
assert_equal("last_read", ex.errors[0].attribute)
end
+ def test_initialize_abstract_class
+ e = assert_raises(NotImplementedError) do
+ FirstAbstractClass.new
+ end
+ assert_equal("FirstAbstractClass is an abstract class and can not be instantiated.", e.message)
+ end
+
+ def test_initialize_base
+ e = assert_raises(NotImplementedError) do
+ ActiveRecord::Base.new
+ end
+ assert_equal("ActiveRecord::Base is an abstract class and can not be instantiated.", e.message)
+ end
+
def test_create_after_initialize_without_block
cb = CustomBulb.create(:name => 'Dude')
assert_equal('Dude', cb.name)

0 comments on commit d3adfd6

Please sign in to comment.