[RUBY] [Path specification] Path specification of nested resources

Overview

I was confused about how to specify the path 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'

How to specify

** Conclusion: ** rails routes to list and check the routes!

(Example) Specify the path in the request test of Rspec

Suppose you have declared routing like this:

routes.rb


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

rails routes in the terminal will list the routes.

                   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)

Based on this, you can specify the path and it's OK!

comments_spec.rb


(abridgement)
    it "Comments with valid content can be registered" 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](https://railsguides.jp/routing.html#%E3%83%8D%E3%82%B9%E3%83%88%E3%81%97%E3%81% 9F% E3% 83% AA% E3% 82% BD% E3% 83% BC% E3% 82% B9 "Rails Guide 2.7 Nested Resources")

Recommended Posts

[Path specification] Path specification of nested resources
Nested structure of each
Note on the path of request.getRequestDispatcher