我正在尝试测试我的多态注释创建操作,但我总是在rspec中没有路由匹配错误。
class CommentsController < ApplicationController
before_action :authenticate_user!
def create
@comment = @commentable.comments.new(comment_params)
@comment.user_id = current_user.id
@comment.save
redirect_to :back, notice: "Your comment was successfully posted."
end
private
def comment_params
params.require(:comment).permit(:body)
end
end
Rspec的
describe "POST #create" do
context "with valid attributes" do
before do
@project = FactoryGirl.create(:project)
@comment_attr = FactoryGirl.build(:comment).attributes
end
it "creates a new comment" do
expect{
post :create, params: { project_id: @project, comment: @comment_attr }
}.to change(Comment, :count).by(1)
end
end
end
我正在使用这种方法在我的另一个控制器中测试创建动作,并且有一切都很好,但是由于某种原因,抛出错误。我认为我的错误符合我传递params以发布创建操作但我没有看到错误。
更新
resources :projects do
resources :comments, module: :projects
resources :tasks do
resources :comments, module: :tasks
end
end
更新2
失败/错误:post:create,params:{project_id:@ project, 可评论:@ project,评论:@comment_attr}
的ActionController :: UrlGenerationError: 没有路线匹配{:action =&gt;&#34;创建&#34;,:评论=&gt; {&#34; id&#34; =&gt; nil,&#34; commentable_type&#34; =&gt; nil, &#34; commentable_id&#34; =&gt; nil,&#34; user_id&#34; =&gt; nil, &#34; body&#34; =&gt;&#34; MyText&#34;,&#34; created_at&#34; =&gt; nil,&#34; updated_at&#34; =&gt; nil, &#34;附件&#34; =&gt; nil},:commentable =&gt;#,: controller =&gt;&#34;评论&#34;,:project_id =&gt;#}
答案 0 :(得分:0)
我认为您的控制器命名空间与您定义的路由不匹配。控制器被定义为不嵌套(CommentsController
),而相应的路由也嵌套在模块projects
内。嵌套路由对ActionDispatch正在寻找的控制器没有影响。但是为路由定义模块将导致rails期望模块命名空间内的控制器。在您的情况下,Projects::CommentsController
和Tasks::CommentsController
。有关详细信息,请参阅"2.6 Controller Namespaces and Routing" of "Rails Routing from the Outside In"。
我将您的路线添加到全新的rails项目并运行rails routes
。输出是:
Prefix Verb URI Pattern Controller#Action
project_comments GET /projects/:project_id/comments(.:format) projects/comments#index
POST /projects/:project_id/comments(.:format) projects/comments#create
...
您可以从路径中删除模块定义
resources :projects do
resources :comments
resources :tasks do
resources :comments
end
end
或将控制器嵌套在项目/任务命名空间中。鉴于你想要评论的多态性,我建议使用第一个选项。