rspec-rails - 没有路线匹配 {: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
?
解决方案
我解决了这个问题:我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
推荐阅读
- wordpress - 页面构建器中的 Wordpress RSS 提要
- wordpress - 联系表格 7 中的按钮单击和自动选择单选按钮
- sql - Python中的子查询
- linux - 如何修复“错误:未找到 .desktop 文件”以手动创建 AppImage
- python - Tensorflow Keras 模型 Load_Model 无法使用 Python 隐藏模型对象
- java - 从远程存储库安装 Maven 工件,如 npm install
- java - 如何不按位置而是按表sqlite中的_id切换到新Activity
- laravel - 未定义的变量停止 if else 语句工作
- react-native - useRef 钩子不适用于 lottie-react-native
- android - Scoped Storage:如何通过 MediaStore 删除多个音频文件?