首页 > 解决方案 > 没有路线匹配 {:action=>"show", :controller=>"products"},缺少必需的键:[:id]

问题描述

我有一个失败的 rSpec 控制器测试

索引路由将有一个索引路由:id中不存在的。

我有干净的路线:

resources :products

这是控制器,

class ProductsController < ApplicationController
  before_action :set_product, only: [:show]
  skip_before_action :authorize_request, only: [:show, :index]

  # GET /products
  def index
    # params here {"controller"=>"products", "action"=>"index", "product"=>{}}
    @products = Product.all

    render json: @products
  end
ActionController::UrlGenerationError: No route matches {
:action=>"show", 
:controller=>"products"}, 
missing required keys: [:id]

为什么叫“秀”?我没有将任何参数传递给控制器​​:这是规范:


RSpec.describe "/products", type: :request do

  describe " GET /index" do
    it " renders a successful response " do
      Fabricate.times(3, :product)
      get "/products", headers: valid_headers
      expect(response).to be_successful
    end
  end
end

当我更改路由get "/products", to: 'products#index'并注释掉时,resources :products它通过了测试

编辑/发现问题:

include Rails.application.routes.url_helpers在我的产品模型中使用,这导致了这个问题。我需要它来生成 URL 来检索我的附件。我还能如何获取 的 URL ActiveStorage

标签: rspec-railsruby-on-rails-6actioncontroller

解决方案


我解决了这个问题:我include Rails.application.routes.url_helpers的产品模型中有导致问题的:

class Product < ApplicationRecord
 # include Rails.application.routes.url_helpers
end

注释掉,所有规格现在都通过了

但我仍然不明白为什么我不能在我的模型中使用它。

我想包含它来检索我的附件的网址:

  def main_image_thumb_url
    rails_blob_url(main_image, host: "localhost:3000")
  end

推荐阅读