將首頁設到 courses#index

至此,我們首頁還是在 Rails 的預設歡迎頁面。我們希望 Homepage 可以指到 courses#index 上。

要檢查 routing 可以寫 Routing specs

新增 routing spec:

mkdir -p spec/routing
touch spec/routing/homepage_spec.rb

編輯 spec/routing/homepage_spec.rb

require "rails_helper"

RSpec.describe "Homepage" do
  it "route root path to course # index" do
    expect(get: "/").to route_to(controller: "courses", action: "index")
  end
end

執行測試:

$ rspec spec/routing
F

Failures:

  1) Homepage route root path to course # index
     Failure/Error: expect(get: "/").to route_to(controller: "courses", action: "index")
       No route matches "/"
     # ./spec/routing/homepage_spec.rb:5:in `block (2 levels) in <top (required)>'

Finished in 0.02384 seconds (files took 1.25 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/routing/homepage_spec.rb:4 # Homepage route root path to course # index

抱怨找不到 routing。

編輯 config/routes.rb,加入

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  resources :courses

  root "courses#index" # <-- 加入這一行
end

測試通過!

$ rspec spec/routing
.

Finished in 0.00623 seconds (files took 1.19 seconds to load)
1 example, 0 failures

results matching ""

    No results matching ""