1
votes

I am getting the following error while testing my CommentsController with RSpec:

ActionController::UrlGenerationError: 
  No route matches {:action=>"create", :comment=>{:comment=>"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, :controller=>"comments"}

spec/models/comment_spec.rb

RSpec.describe CommentsController, type: :controller do
  let!(:user) { create(:user) }
  let!(:post1) { create(:post, user: user) }
  let!(:comment) { create(:comment, user_id: user.id, post_id: post1.id) }
  let!(:comment_attributes) { attributes_for(:comment) }

  describe "#create" do
    before do
      sign_in user
    end

    it 'save post' do
      expect do
        post :create, params: { comment: comment_attributes }, session: {}
      end.to change(Comment, :count).by(1)
    end

    it 'if post saves, redirect_to posts page' do
      post :create, params: { post: comment_attributes }, session: {}
      expect(response).to redirect_to(posts_path)
    end
  end
end
1
spec/models/comment_spec.rb for a Controller spec you should have the spec file in a directory for controllers. eg: spec/controllers/comments_controller_spec.rb. That way RSpec will be able to automatically determine what kind of test is being performed, and you can remove type: :controller from the describe method.Tom

1 Answers

2
votes

You have to update your routes.rb file every time you create a new resource (that you want to access via link), otherwise Rails don't know which controller to use with a given URL. Adding a resources :comments line in routes.rb should do it for you.