问题
I'm using acts_as_commentable in a Rails app to allow commenting on different types of models.
I've got a polymorphic CommentsController
ala the Polymorphic Association Railscast.
I'm trying to write specs for this controller; however, I'd like to use acts_as_fu to define a generic Commentable
class for the controller to use in the specs. This way its not tied to one of our concrete commentable models.
The problem is that when I try to test the controller actions I get routing errors because there are no routes for the Commentable
class I created using acts_as_fu.
I need a way to draw the routes for this dynamically created model in a before(:all)
(using RSpec by the way) for the specs.
Here's what my spec looks like so far:
describe CommentsController do
before(:all) do
# Using acts_as_fu to create generic Commentable class
build_model :commentable do
acts_as_commentable :comment
belongs_to :user
attr_accessible :user
end
# TODO - Initialize Commentable routes
end
end
UPDATE: Found a 'hacky' solution. I'm wondering if there's a cleaner way of doing this though.
回答1:
Found a solution for adding routes at runtime in Rails 3, albeit a hacky one:
describe CommentsController do
before(:all) do
# Using acts_as_fu to create generic Commentable class
build_model :commentable do
acts_as_commentable :comment
belongs_to :user
attr_accessible :user
end
# Hacky hacky
begin
_routes = Rails.application.routes
_routes.disable_clear_and_finalize = true
_routes.clear!
Rails.application.routes_reloader.paths.each{ |path| load(path) }
_routes.draw do
# Initialize Commentable routes
resources :commentable do
# Routes for comment management
resources :comments
end
end
ActiveSupport.on_load(:action_controller) { _routes.finalize! }
ensure
_routes.disable_clear_and_finalize = false
end
end
end
来源:https://stackoverflow.com/questions/18706713/how-to-dynamically-add-routes-in-rails-3-2