ActionController :: UrlGenerationError:没有路由匹配(Rspec)

时间:2018-12-27 08:40:11

标签: ruby-on-rails rspec

使用CommentsController测试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 个答案:

答案 0 :(得分:2)

每次创建新资源(要通过链接访问)时,都必须更新routes.rb文件,否则Rails不知道在给定URL中使用哪个控制器。在resources :comments中添加routes.rb行可以为您完成此操作。