17

I'm trying to instantiate an object of abstract AR class for testing purposes. The model's defined like this:

class Basic < ActiveRecord::Base
  self.abstract_class = true

  def stuff
    raise NotImplementedError
  end
end

When I try to Basic.new, I get:

"Mysql2::Error: Table 'project_development.basics' doesn't exist"

Is it normal behavior? Do abstract AR classes are not intended to be instantiated even without (obviously impossible) persistence?

Using 1.9.2-p136 with Rails 3.0.4 / Mysql2 0.2.6

Edit:

It turns out that the error is caused by column definitions, which in the case of an abstract model cannot be fetched from the database.

class Basic < ActiveRecord::Base
  self.abstract_class = true
  @columns = []
end

Works like a charm.

Adrian Pacala
  • 1,011
  • 1
  • 8
  • 12
  • Ruby programmers tend to dislike abstract classes. Including modules does not work for you? http://stackoverflow.com/questions/512466/how-to-implement-an-abstract-class-in-ruby – tokland Feb 17 '11 at 11:27
  • 3
    @tokland; Really? I'd have to disagree with that. Abstract classes are very useful and are used very often. `ActiveRecord::Base` is an abstract class, for example. I do agree that the way some people use abstract classes could be better served by using modules, though. – idlefingers Feb 17 '11 at 11:58
  • @idlefingers. Sorry, that was too bold a statement, indeed abstract classes may be useful in certain scenarios. – tokland Feb 17 '11 at 12:07

1 Answers1

20

This is normal behaviour. Abstract classes are not supposed to be instantiated. You should test the classes which inherit from the abstract class, not the abstract class itself.

idlefingers
  • 31,659
  • 5
  • 82
  • 68
  • +1, this is typical in many dynamic languages. Related: http://stackoverflow.com/questions/4619941/simulating-abstract-classes-in-ruby-rails – tokland Feb 17 '11 at 12:10