I am trying to test my polymorphic comments create action but I always get no route matches error in 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
I am using this approach for testing create action in my another controllers and there is everything good, but here from some reason is throws error. I think my error is in line where I pass params to post create action but I do not see error.
UPDATE
resources :projects do
resources :comments, module: :projects
resources :tasks do
resources :comments, module: :tasks
end
end
UPDATE 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=>#}
@commentablein your controller? And seeingroutes.rbwould help as well, in addition to the rest of the test file you've excerpted. - Jim Van Fleet@commentableisnilbased on what we see above. Is it a helper inApplicationController? Are you getting 404s in your test logs or 500s? - Jim Van FleetNo route matches {:controller => "comments", :action => "create"}is a very different error thanNo route matches {:controller => "unicorns", :action => "rainbows"}orNo route matches [POST] /projects/:project_id/comments- engineersmnky