【问题标题】:ActionController::UrlGenerationError: No route matches (Rspec)ActionController::UrlGenerationError: 没有路由匹配 (Rspec)
【发布时间】:2019-05-25 07:23:15
【问题描述】:

在使用RSpec 测试我的CommentsController 时出现以下错误:

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

【问题讨论】:

  • spec/models/comment_spec.rb 对于控制器规范,您应该将规范文件放在控制器目录中。例如:spec/controllers/comments_controller_spec.rb。这样,RSpec 将能够自动确定正在执行哪种测试,并且您可以从 describe 方法中删除 type: :controller

标签: ruby-on-rails rspec


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多