1

我正在为可评论功能构建一个新的 rails3.1 引擎。

我创建了引擎,生成了名为Comment.

发动机config/routes.rb有:

Kurakani::Engine.routes.draw do
  resources :comments
end

spec/dummyrails 应用程序有一个名为的资源,Post它的路由有:

Rails.application.routes.draw do

  resources :posts do
    resources :comments
  end

  mount Kurakani::Engine => "/kurakani"
end

我已经设置了引擎的 Comment 模型和虚拟 Rails 应用程序的 Post 模型之间的关联。

然后在spec/dummyRails 应用程序中,我在showPost 的模板中呈现了评论表单。表单也会生成,其动作路径为post/1/comments.

当我运行规范时,我认为它会尝试在应用程序本身内部搜索控制器,spec/dummy而不是提交到引擎的app/controllers/kurakani/comments_controller.rb,所以当我运行规范时出现以下错误。

$ bundle exec rspec spec/integration/comments_spec.rb                                                                           ruby-1.9.2-p180
No examples matched {:focus=>true}. Running all.
Run filtered excluding {:exclude=>true}

/Users/millisami/gitcodes/kurakani/app/views/kurakani/comments/_form.html.erb:3:in `___sers_millisami_gitcodes_kurakani_app_views_kurakani_comments__form_html_erb___1787449207373257052_2189921740'
F

Failures:

  1) Kuraki::Comment authenticated user creating a new comment
     Failure/Error: click_button "Create"
     ActionController::RoutingError:
       uninitialized constant CommentsController
     # ./spec/integration/comments_spec.rb:29:in `block (3 levels) in <top (required)>'

如何指定要提交给引擎comments_controller.rb而不是spec/dummy应用程序的评论?

如果我不能把问题说清楚,我已经在https://github.com/millisami/kurakani推送了 repo

4

1 回答 1

0

The problem is that your route for the form that is generated goes to /posts/:post_id/comments, which is the route defined in your application, but not your engine. Your engine only defines this route:

resources :comments

This is (almost) working because the engine sees that the application has the route which matches to CommentsController, it's just that there's no CommentsController for it to go to.

I downloaded the application from GitHub and had a play around and changed the form_for in app/views/kurakani/comments/_form.html.erb to be this:

form_for(Kurakani::Comment.new, :url => kurakani.comments_path)

This makes the test pass, but I am not sure if it actually gives you what you want. You're probably going to want to play around with that URL part yourself.

What's happening here is that this view is rendered by the main application using the kurakani_list helper in spec/dummy/app/posts/show.html.erb, meaning that any URL helper that you reference (directly or indirectly) will point to the application and not to the engine, like I think you want it to.

So in order to tell Rails what the true route is that we want our form to go to we must specify the :url option and tell it we want to go to kurakani.comments_path, rather than the comments_path which may be defined by the application.

If we wanted to do the reverse (reference an application route from within an engine), we would use main_app rather than kurakani.

于 2011-06-17T09:22:51.973 回答