kikki's tech note

技術ブログです。UnityやSpine、MS、Javaなど技術色々について解説しています。

windowsユーザが学ぶmacブックでのRails開発 vol.2

本章では、前章に引き続き、Railsでの動的処理について確認したいと思います。kikki.hatenablog.com

目的

本章では、HTMLのtitleタグが以下のように、action名に応じて変化するWebサイトを作ります。

Ruby on Rails Tutorial Sample App | 【アクション名】

プログラムの改修

ストファイルの変更

前章までに作成したテストファイルを今回の処理変更に合わせるために、書き換えます。テスト内容は、titleタグにaction名が含まれることです。
【test/integration/static_pages_test.rb】

require 'test_helper'

class StaticPagesTest < ActionDispatch::IntegrationTest
 test "should have the content, 'home'" do
  get '/static_pages/home'
  assert_select 'h1', 'StaticPages#home'
 end

 # 本章でのテスト追加分

 test "should have the title 'Home'" do
  get '/static_pages/home'
  assert_select 'title', 'Ruby on Rails Tutorial Sample App | Home'
 end

 test "should have the title 'Help'" do
  get '/static_pages/help'
  assert_select 'title', 'Ruby on Rails Tutorial Sample App | Help'
 end
end

Controllerの変更

ActionにViewで利用される変数を用意します。
【app/controllers/static_pages_controller.rb】

class StaticPagesController < ApplicationController
 def home
  @title = "Home"
 end
 def help
  @title = "Help"
 end
end

Viewの変更

どのアクションにおいても、titleタグがControllerより反映されるよう、変更します。
【app/views/layout/application.html.erb】

<!DOCTYPE html>
<head>
 <title>Ruby on Rails Tutorial Sample App | <%= @title %></title>
 <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
 <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
 <%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
</body>
</html>

テストの実行

最後にテストを実施し、正しく表示されることを確認します。

rake test test/integration/static_pages_test.rb

筆休め

本章では、Railsを用いて動的ページをテスト駆動で改修しました。今後は、データベースを利用したプログラムへと調整したいと思います。

以上、「windowsユーザが学ぶmacブックでのRails開発 vol.2」でした。


※無断転載禁止 Copyright (C) kikkisnrdec All Rights Reserved.