Warning: Toplevel Constant XYZ Referenced Admin:XYZ

Back | rspec, rails, ruby | 1/8/2012 |

I posted this to a Ruby forum a while ago.

I got controllers in a namespace and controllers outside of the namespace. For example, I have a PagesController and a Admin::PagesController. When I run rspec from the top, tests pass and I get the following warning: spec/controllers/admin/pages_controller_spec.rb:4: warning: toplevel constant PagesController referenced by Admin::PagesController. This makes no sense. I do have a PagesController and an Admin::PagesController and specs for both that are declared properly.

This was only happening under Spork, so I posted a similar question to the sporkgem list.

I also found a workaround, to require the Admin controllers first in spec/spec_helper.rb.

  1. Dir[File.expand_path("app/controllers/admin/*.rb")].each do |file|
  2.   require file
  3. end

Finally, @tilsammans figured it out. It’s the same problem as what I have: an Admin namespace and an Admin class.

It was because I also had a class Admin, as well as a namespace Admin. Since Admin was a class (a model) it inherited from Object which made the top-level ApplicationController available inside the Admin namespace. The reply by Andrew White on http://groups.google.com/group/rubyonrails-core/browse_thread/thread/bab5e87ee10d2ecb lead me to find the right answer. In the end I renamed Admin to AdminUser and everything fell into place.

This is rather counterintuitive and one would think Ruby should somehow handle this situation, but it at least makes technical sense.