Monday, 12 August 2013

Getting uninitialized constant (NameError) inside decorators when running rspec tests via rake

Getting uninitialized constant (NameError) inside decorators when running
rspec tests via rake

In my app I use an engine (blogit) to which I want to add some changes /
behaviours. I followed the guides on how to override engine
controllers/models and added the following:
In config/initializer/blogit.rb
# Requires extension ruby files in lib/blogit.
Dir[Rails.root.join("lib/blogit/*.rb")].each {|f| require f}
In lib/blogit/engine.rb
module Blogit
class Engine < ::Rails::Engine
isolate_namespace Blogit
config.to_prepare do
Dir.glob(Rails.root +
"app/decorators/**/blogit/*_decorator*.rb").each do |c|
require_dependency(c)
end
end
end
end
In app/decorators/controllers/blogit/comments_controller_decorator.rb
Blogit::CommentsController.class_eval do
def create
Rails.logger.info "decorated controller action"
# ... overridden stripped ...
end
end
In app/decorators/models/blogit/comment_decorator.rb
Blogit::Comment.class_eval do
belongs_to :user
end
To be mentioned:
I have also created a migration to add a user reference to the comments
model, since my app uses devise and I only want logged_in users to be able
to comment. Therefore I don't need the standard behaviour, so I'm going to
override it.
Adding require "blogit" or require "blogit/comments_controller" doesn't help.
The Problem
If I run rake I get the weird error:
/Users/Kassi/.rvm/rubies/ruby-1.9.3-p392-railsexpress/bin/ruby -S rspec
./spec/controllers/home_controller_spec.rb ./spec/models/user_spec.rb
/Users/Kassi/demo/app/decorators/controllers/blogit/comments_controller_decorator.rb:3:in
`<top (required)>': uninitialized constant Blogit::CommentsController
(NameError)
However, if I run the first line that rake mentions by hand (.../ruby -S
...), all tests are being run successfully.
The app itself runs fine, i.e. it starts without errors and I'm able to
comment as I want. My decorator action code is being executed.
The Code
Since this problem is part of a bigger project, I created a new app from
scratch for testing purposes that contains only the relevant stuff: basic
rails app, rspec, devise, blogit and the decorators. It can be found here:
git@github.com:kassi/decorator_demo.git
I haven't created nice views or menus. Sorry for that. You would have to
type the routes in your browser to sign_up (/users/sign_up) and to the
blog (/blog).
I hope it helps.

No comments:

Post a Comment