[Ruby] [Path designation] Nested resource path designation

less than 1 minute read

Overview

I am confused about the path specification method of the nested resource for a moment, so I will record it as a memorandum.

Environment

・Ruby ‘2.5.7’ ・Rails ‘5.2.3’ ・Rspec-rails ‘4.0.0.beta2’

Specifying method

**Conclusion: ** rails routes to list and verify routes!

(Example) Specify the path in Rspec request test

If you declare a route like this:

routes.rb


  resources :datespots do
    resources :comments, only: [:create, :destroy]
  end

If you do rails routes in the terminal, a list of routes will be displayed.

                   Prefix Verb URI Pattern Controller#Action
(abridgement)
        datespot_comments POST /datespots/:datespot_id/comments(.:format) comments#create
         datespot_comment DELETE /datespots/:datespot_id/comments/:id(.:format) comments#destroy
(abridgement)

If you specify the path based on this, OK!

comments_spec.rb


(abridgement)
    it "Be able to register comments with valid contents" do
      expect {
        post "/datespots/#{datespot.id}/comments", params: {
          datespot_id: datespot.id,
          comment: {content: "It's fashionable!"}
        }
      }.to change(datespot.comments, :count).by(1)
    end
(abridgement)

Reference

Rails Guide 2.7 Nested Resources