如何提交在主应用程序中呈现的rails3.1引擎表单以提交给引擎的控制器?

时间:2011-06-10 07:58:06

标签: ruby-on-rails-3 ruby-on-rails-3.1

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

我创建了引擎,生成了名为Comment的资源。

引擎的config/routes.rb有:

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

spec/dummy rails app有一个名为Post的资源,其路由包含:

Rails.application.routes.draw do

  resources :posts do
    resources :comments
  end

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

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

然后在spec/dummy rails app中,我已经在帖子的show模板中呈现了评论表单。 该表单还会生成其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

推送回购

1 个答案:

答案 0 :(得分:0)

问题是您生成的表单的路由是/posts/:post_id/comments,这是应用程序中定义的路由,而不是引擎 。您的引擎仅定义此路线:

resources :comments

这(几乎)正常工作,因为引擎看到应用程序的路由与CommentsController匹配,只是没有CommentsController才能进入。

我从GitHub下载了该应用程序并进行了游戏,并将form_for中的app/views/kurakani/comments/_form.html.erb更改为:

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

这使测试通过,但我不确定它是否真的能给你你想要的东西。你可能想要自己玩这个URL部分。

这里发生的是这个视图由主应用程序使用kurakani_list中的spec/dummy/app/posts/show.html.erb帮助器呈现,这意味着您引用的任何URL帮助程序(直接或间接)将指向应用程序而不是引擎,就像我想你想要的那样。

因此,为了告诉Rails我们希望我们的表单转到哪个真正的路由,我们必须指定:url选项并告诉它我们要转到{{1而不是应用程序定义可能kurakani.comments_path

如果我们想要反向(从引擎内引用应用程序路径),我们将使用comments_path而不是main_app