2017-09-22 51 views
0

我想測試我的多態註釋創建操作,但我總是在rspec中沒有路由匹配錯誤。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來發布創建操作的內容,但我沒有看到錯誤。

UPDATE

resources :projects do 
    resources :comments, module: :projects 
    resources :tasks do 
     resources :comments, module: :tasks 
    end 
    end 

更新2

Failure/Error: post :create, params: { project_id: @project, commentable: @project, comment: @comment_attr }

ActionController::UrlGenerationError: No route matches {:action=>"create", :comment=>{"id"=>nil, "commentable_type"=>nil, "commentable_id"=>nil, "user_id"=>nil, "body"=>"MyText", "created_at"=>nil, "updated_at"=>nil, "attachment"=>nil}, :commentable=>#, :controller=>"comments", :project_id=>#}

+0

什麼是在你的控制器中設置@ @ commentable?除了你已經摘錄的測試文件的其餘部分外,看到'routes.rb'也會有所幫助。 –

+0

@JimVanFleet更新了我的問題與路線。可評論的是項目或任務,但我試圖在評論項目時測試案例。 –

+1

我理解你的意圖,但基於我們上面看到的,「@ commentable」是'nil'。它是'ApplicationController'中的助手嗎?你在測試日誌或500s中獲得404s嗎? –

回答

0

我認爲你的控制器命名空間不匹配定義的路由。控制器被定義爲不嵌套(CommentsController),而相應的路由嵌套在模塊projects內。嵌套路線對ActionDispatch正在尋找的控制器沒有影響。但是爲路線定義一個模塊將導致rails期望模塊名稱空間中的控制器。在你的情況下,這將是Projects::CommentsControllerTasks::CommentsController。詳情請參閱"2.6 Controller Namespaces and Routing" of "Rails Routing from the Outside In"

我將您的路線添加到全新的導軌項目並運行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 

或窩在一個項目/任務名稱空間中刪除的模塊定義中的控制器。鑑於你想爲你的評論多態,我會建議使用第一個選項。