我想測試我的多態註釋創建操作,但我總是在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=>#}
什麼是在你的控制器中設置@ @ commentable?除了你已經摘錄的測試文件的其餘部分外,看到'routes.rb'也會有所幫助。 –
@JimVanFleet更新了我的問題與路線。可評論的是項目或任務,但我試圖在評論項目時測試案例。 –
我理解你的意圖,但基於我們上面看到的,「@ commentable」是'nil'。它是'ApplicationController'中的助手嗎?你在測試日誌或500s中獲得404s嗎? –