Railsチュートリアル 3章 静的なページ

Railsチュートリアル3章をやって大事だと思ったことメモしていきます!

尚、テストコードはRspecを利用して書きました。

 

静的ページのルーティング、コントローラー

 

ルーティング

Rails.application.routes.draw do
root 'static_pages#home'
get 'static_pages/home'
get 'static_pages/help'
get 'static_pages/about'
get 'static_pages/contact'
resources :users

end

getの4つが静的なページのルーティング。

root_pathは#であるところがちがう。

コントローラー名/アクション名って感じだね。

 

コントローラー

class StaticPagesController < ApplicationController
def home
end

def help
end

def about
end

def contact
end
end

 

provideとyeild

application.html.erb

<!DOCTYPE html>
<html>
<head>
<title><%= yield(:title) %> | Ruby on Rails Tutorial Sample App</title>
       ここ!!
<%= csrf_meta_tags %>
<%= csp_meta_tag %>

<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>

<body>
<%= yield %>
</body>
</html>

 

home.html.erb

<% provide(:title, "Home") %>
  ここ!!
<h1>Sample App</h1>
<p>
This is the home page for the
sample application.
</p>

 

provideで設定したやつをyeildで呼び出してるイメージ。

そうすることでprovide内で書いたことをyeildで埋め込んでいる。

 

テストコード

static_pages_spec.rb

require 'rails_helper'

RSpec.describe "StaticPages", type: :system do
 
def setup
@base_title = "Ruby on Rails Tutorial Sample App"
end

it 'should get root' do
visit root_path
expect(current_path).to eq root_path
ページを訪れたときにちゃんとそのページに移れてるかをテスト
expect(page).to have_title "Home | #{@base_title}"
タイトルをテストするときはhave_titleを使う。これはhave_contentと使い方一緒である。
#{@base_title}としているのは同じコードが繰り返されているから上のsetupでまとめている。式を利用して文字列に
入れてあげてる。

end

it 'should get home' do
visit static_pages_home_path
expect(current_path).to eq (static_pages_home_path)
expect(page).to have_title "Home | #{@base_title}"

end

it 'should get help' do
visit static_pages_help_path
expect(current_path).to eq (static_pages_help_path)
expect(page).to have_title "Help | #{@base_title}"

end

it 'should get about' do
visit static_pages_about_path
expect(current_path).to eq (static_pages_about_path)
expect(page).to have_title "About | #{@base_title}"

end

it 'should get contact' do
visit static_pages_contact_path
expect(current_path).to eq (static_pages_contact_path)
expect(page).to have_title "Contact | #{@base_title}"

end


end

 

system specではgetやpost----pathやrender_template等は使えないと思われる。

visit pathおk

urlもだめ。path◯

 

3章は以上です!