【问题标题】:No route matches {:action=>"show", :controller=>"products"}, missing required keys: [:id]没有路线匹配 {:action=>"show", :controller=>"products"},缺少必需的键:[:id]
【发布时间】:2021-03-15 18:01:35
【问题描述】:

我有一个失败的 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 来检索我的附件。我还能如何获取ActiveStorage 的网址?

【问题讨论】:

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


    【解决方案1】:

    我解决了问题:我的产品模型中有 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
    

    【讨论】:

      猜你喜欢
      • 2016-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多