rspec-railsruby-on-rails-6actioncontroller

No route matches {:action=>"show", :controller=>"products"}, missing required keys: [:id]


I have a rSpec Controller test which fails

the index route will have an :id which does not exist in an index route.

I've clean routes:

resources :products

This is the controller,

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]

Why is "show" called? I did not passed any params to the controller: This is the spec:


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

When I change the routes from get "/products", to: 'products#index' and comment out resources :products then it passes the test

EDIT / PROBLEM FOUND :

I use include Rails.application.routes.url_helpers in my Product model, which caused this issue. I need it to generate URLs to retrieve my attachments. How else can I get the URLs of ActiveStorage ?


Solution

  • I solved the problem: I had include Rails.application.routes.url_helpers in my Product model which caused the problem:

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

    commented out, all specs are passing now

    But I still don't understand why I can't use it in my Model.

    I wanna have it included to retrieve urls of my attachments:

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