MENU

挫折しないRailsチュートリアルのまとめ【第3章】

Railsチュートリアルの3章を走破しました。

2章までは自分なりにまとめたりしてましたが、3章からはやったこと、つまずいたことのメモにしようと思います。

目次

目次

3章の内容

ほぼ静的なページを作成しながら以下を学習する。

3章の内容
  • コントローラの自動作成方法
  • コントローラの手動作成方法
  • 自動テスト方法
  • テストから行う開発方法
  • ビューの構成(レイアウト)

3.1 セットアップ

「sample_app」というRailsアプリケーションを作成します。

Railsアプリケーションの作成(rails new)

自分は推奨環境であるAWS Cloud9で学習していたので、1章、2章と同じワークスペースに作成しました。

$ cd environment/
$ rails _5.1.6_ new sample_app

今回はなんでバージョン指定っぽいのが入ってるんだろう?と思ったら、1章、2章でも指定していましたね。

バージョンを省略すると、環境にインストールされている最新のRailsでアプリケーションが作成されるため、RailsチュートリアルでインストールしたRailsのバージョンで進めるためにバージョンを指定しているんですね。
(バージョンが異なるとテキストと異なる挙動をする可能性があるため)

1章、2章では完全に見落としてましたが、AWS Cloud9の環境にはRailsチュートリアルで使用しているRails5.1.6しかインストールされていないので、助かってたんですね。

rails newでバージョンを指定する理由はこちらを参照させていただきました。
Railsチュートリアルでrails newするときはバージョンを指定しよう

あと役に立ちそうなRails newのよく使うオプション一覧
rails newするときによく使うオプションと、rails newした後によく行う設定

Gemfileの修正

Railsチュートリアルに記載されている内容にGemFileを書き換えます。

GemFileに場所は「sample_app/Gemfile」です。

bundle install

本番(production)環境用のgemはインストールしないように「–without production」オプションを使用して「bundle install」を実行

 cd sample_app/
$ bundle install --without production
The dependency tzinfo-data (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mingw32, x86-mswin32, x64-mingw32, java. To add those platforms to the bundle, run `bundle lock --add-platform x86-mingw32 x86-mswin32 x64-mingw32 java`.
Fetching gem metadata from https://rubygems.org/............
Fetching gem metadata from https://rubygems.org/.
You have requested:
  spring = 2.0.2

The bundle currently has spring locked at 2.1.0.
Try running `bundle update spring`

If you are updating multiple gems in your Gemfile at once,
try passing them all to `bundle update`
$

「bundle update」をしろと怒られます。

ちなみに「bundle install –without production」を実行したタイミングで、「sample_app/.bundle/config(隠しファイル)」が以下のようになり、本番環境にデプロイする時に本番環境用のgemがインストールされないようになっているので、本番環境にデプロイするときは記述内容を削除(コメント化)する必要があります。

---
BUNDLE_WITHOUT: "production"

# 本番環境にデプロイする時はコメント化する
# BUNDLE_WITHOUT: "production"

では、「bundle update」を実行します。

$ bundle update
The dependency tzinfo-data (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mingw32, x86-mswin32, x64-mingw32, java. To add those platforms to the bundle, run `bundle lock --add-platform x86-mingw32 x86-mswin32 x64-mingw32 java`.
Could not find gem 'rails-controller-testing (= 1.0.2)' in any of the gem sources listed in your Gemfile.

「rails-controller-testing 1.0.2」がないと怒られます。

以下の記事で「bundle install」と「bundle update」の違いを確認してみます。
「Gemfile」と「Gemfile.lock」の違いまで書かれていて分かりやすいです。
bundle install と bundle updateの違いについて

「bundle update」を「Gemfile」をもとにインストールするので、「Gemfile」に記載されている「gem ‘rails-controller-testing’, ‘1.0.2’」はもうインストールできないってことなのでしょうか?

gemをインストールした結果である「Gemfile.lock」を確認すると以下の記述があります。

 ・
 ・
 ・
      rails-dom-testing (~> 2.0)

 ・
 ・
 ・

これはrails-controller-testingは2.0がインストールされたということでしょうか。

ちなみに「~>」や「>=」は以下のような意味なので、次に「bundle install」を実行した時に、2.0.1〜2.1のバージョンがあればインストールするということになるので、やっぱりrails-controller-testingは2.0がインストールされているっぽいです。

  • >=バージョン:常に最新バージョンをインストールする
  • ~>バージョン:マイナーバージョンの最新をインストールする

なのでとりあえず先に進めます。

Gitリポジトリを初期化

# リポジトリを管理するディレクトリ(アプリケーションのルートディレクトリ)に移動
$ cd sample_app

# リポジトリを初期化
$ git init

# 全てのファイルをインデックスに追加
$ git add -A

# インデックスに追加された変更ファイルををコミット
$ git commit -m "Initialize repository"

README.mdを更新

アプリケーションのルートディレクトリにある「README.md」に具体的な作業内容をわかりやすく記入したほうが良いとあるんで、Railsチュートリアルに記載されている「README.md」の内容をコピペし、変更内容をコミットします。

git commit -am "Improve the README"

git commitの「-am」オプションは「-a」オプションと「-m」オプションの2つを同時に行ってくれるオプションです。という風にここで説明してますけど、2章でもさらっと使われてましたけど・・・。

Bitbucket上にリポジトリを作成

Bitbucket上にリポジトリ情のリポジトリ作成手順は2章のまとめ記事に書いたのでそちらを参照。

Bitbucketにプッシュ

以下のコマンドを実行して、Bitbucket上のリポジトリにプッシュします。

# リモートリポジトリを登録
$ git remote add origin git@bitbucket.org:Bitbucketのユーザー名/sample_app.git

# 全てのファイルと参照先をプッシュ
$ git push -u origin --all

helloアクションをApplicationコントローラーに追加

1章、2章と同じようにhelloアクションを作成します。

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  # helloアクション
  def hello
    render html: "hello, world!"
  end
end

helloアクション用のルーティングを設定する

helloアクションをルートとするようにルーティングを設定します。

Rails.application.routes.draw do
  root 'application#hello'
end

変更内容をコミットしてプッシュ。

$ git commit -a -m "Add hello"

$ git push

本番環境のデータベース接続先をPostgreSQLに修正する

本番環境であるHerokuはSQLite3に対応していないため、PostgreSQLに接続するように「config/database.yml」を修正します。

# SQLite version 3.x
 ・
 ・
 ・
# production:
#   <<: *default
#   database: db/production.sqlite3
production:
  <<: *default
  adapter: postgresql
  database: db/production.pg

Herokuにデプロイ(プッシュ)する

今までの内容をHerokuにデプロイ(プッシュ)するため、Herokuにアプリケーションの実行場所を作成します。

# heroku create
Creating app... !
 ▸    You've reached the limit of 5 apps for unverified accounts. Delete some apps or add a credit card to verify your
 ▸    account.

「未確認アカウントのアプリケーション数の上限(5個)に達してるから作成できないよと」怒られました。

1章、2章でデプロイがうまくいかずに「heroku create」を何回か実行したのが、原因でしょうね。

Herokuアプリケーションの削除

通常であればこの作業は不要

下記の記事を参考にしながらHerokuから不要なアプリケーションを削除します。
【herokuコマンド】createからdestroyまで

ブラウザでHerokuにログインして、アプリケーション名を確認します。


左側の文字列がアプリケーション名になります。

# Herokuアプリケーション削除コマンド
$ heroku apps:destroy --app aqueous-dawn-11733
 ▸    WARNING: This will delete ⬢ aqueous-dawn-11733 including all add-ons.
 ▸    To proceed, type aqueous-dawn-11733 or re-run this command with --confirm
 ▸    aqueous-dawn-11733

> 

# アプリケーション名の確認
> aqueous-dawn-11733
Destroying ⬢ aqueous-dawn-11733 (including all add-ons)... done
$

無事削除されました。

他2つも不要なやつなので、削除しておきます。

改めて、Herokuにアプリケーションを作成。

$ heroku create
Creating app... done, ⬢ vast-ocean-83669
https://XXXXXXXXXXX.herokuapp.com/ | https://git.heroku.com/XXXXXXXXXXX.git

無事成功しました。

そして、Herokuにデプロイ(プッシュします)。

$ git push heroku master

Herokuへのデプロイが成功しているか確認する

「heroku create」コマンド実行時に生成されたURLまたは、「heroku open」コマンドで表示されるURLにアクセスし、「hello, World!」のページが表示されるかを確認します。

演習1

BitbucketがMarkdown記法のREADMEをHTMLとして正しく描画しているか、確認する。

演習2

「Herokuへのデプロイが成功しているか確認する」で確認済み。

3.2 静的ページ

静的ページ作成用のgitのブランチを作成し、チェックアウトする。

$ git checkout -b static-pages

3.2.1 静的なページの生成

静的ページ「Homeページ」「Helpページ」「Aboutページ」の3つで構成するので、静的ページ用のコントローラ「StaticPages」と各ページ用のアクションを追加する。

まずは「StaticPages」コントローラと「Homeページ」「Helpページ」アクションを1つのコマンドでまとめて作成する。

$ rails generate controller StaticPages home help

コントローラ名をStaticPagesのようなキャメルケース(単語の頭文字を大文字にしてつなぎ合わせた名前)で登録すると、スネークケース(単語間にアンダースコアを加えて繋ぎ合わせた名前))の名前に変換してコントローラファイル(static_pages_controller.rb)が作成される。
*コントローラ名にスネークケースの名前を指定すると、そのままスネークケースの名前でコントローラファイルが作成される。

コントローラの作成に失敗(名前の記述ミスなど)し場合、コントローラ作成コマンドの「generate」部分を「destroy」にすることで、元に戻す(削除する)ことが可能。

$ rails destroy controller コントローラ名 アクション名

*「generate」コマンでではたくさんのファイルが作成されるため、単にファイルを削除するだけでは、元に戻すことはできない
*コントローラ以外にも「generate」を使用する場合は、「destroy」で元に戻す(削除する)ことが可能。

作成したコントローラ、アクションをGitに登録

作成したコントローラ、アクションをGItに登録する。

# 作成・修正されたファイルを全てインデックス
$ git add -A

# インデックスされたファイルをコミット
$ git commit -m "Add a Static Pages controller"

# static-pagesブランチにプッシュ
$ git push -u origin static-pages

以降はRailsチュートリアル上ではコミット、プッシュのタイミングは指示されないので任意のタイミングでコミット、プッシュを行う。

演習1

Fooというコントローラを生成し、その中にbarとbazアクションを追加する。

  • Fooコントローラ作成コマンド実行
  • config/routes.rb
  • app/controllers/foo_controller.rb
  • app/views/foo/bar.html.erb
  • app/views/foo/baz.html.erb

演習2

Fooコントローラとそれに関連するアクションを削除する。

  • Fooコントローラ削除コマンド実行
  • config/routes.rb
  • コントローラーとビューが削除されている

3.2.2 静的なページの調整

ビューの内容は静的なHTMLページなので、最悪Railsを知らなくても修正できる。

3.3 テストから始める

3.3.1 最初のテスト

テストコマンド「rails test」を使用してテストを実行する。

$ rails test

# 実行結果
Running via Spring preloader in process 21968
/home/ec2-user/environment/sample_app/db/schema.rb doesn't exist yet. Run `rails db:migrate` to create it, then try again. If you do not intend to use a database, you should instead alter /home/ec2-user/environment/sample_app/config/application.rb to limit the frameworks that will be loaded.
Run options: --seed 7410

# Running:

..

Finished in 0.499371s, 4.0050 runs/s, 4.0050 assertions/s.

2 runs, 2 assertions, 0 failures, 0 errors, 0 skips

3.3.2 Red

「rails generate controller StaticPages home help」実行時に自動的に作成されているテストファイル(test/controllers/static_pages_controllertest.rb)に、まだ作成していないAboutページのテストを追加する。

require 'test_helper'

class StaticPagesControllerTest < ActionDispatch::IntegrationTest
 ・
 ・
 中略
 ・
 ・
  test "should get about" do
    get static_pages_about_url
    assert_response :success
  end
end

 

テストコマンドを実行してテストが失敗することを確認する。

$ rails test
Running via Spring preloader in process 22109
/home/ec2-user/environment/sample_app/db/schema.rb doesn't exist yet. Run `rails db:migrate` to create it, then try again. If you do not intend to use a database, you should instead alter /home/ec2-user/environment/sample_app/config/application.rb to limit the frameworks that will be loaded.
Run options: --seed 61370

# Running:

E..

Finished in 0.290192s, 10.3380 runs/s, 6.8920 assertions/s.

  1) Error:
StaticPagesControllerTest#test_should_get_about:
NameError: undefined local variable or method `static_pages_about_url' for #<StaticPagesControllerTest:0x0000000001e109a0>
    test/controllers/static_pages_controller_test.rb:16:in `block in <class:StaticPagesControllerTest>'

3 runs, 2 assertions, 0 failures, 1 errors, 0 skips

3.3.3 Green

3.3.2のテスト結果の「NameError: undefined local variable or method `static_pages_about_url’」からAboutページのURLが存在しないということがわかるので、ルーティングファイル(routes.rb)にAboutページのURLを追記する。

Rails.application.routes.draw do
  get 'static_pages/home'
  get 'static_pages/help'
  get 'static_pages/about'

  root 'application#hello'
end

追記後、テストを再度実行。

$ rails test
Running via Spring preloader in process 4124
/home/ec2-user/environment/sample_app/db/schema.rb doesn't exist yet. Run `rails db:migrate` to create it, then try again. If you do not intend to use a database, you should instead alter /home/ec2-user/environment/sample_app/config/application.rb to limit the frameworks that will be loaded.
Run options: --seed 46989

# Running:

.E.

Finished in 0.305783s, 9.8109 runs/s, 6.5406 assertions/s.

  1) Error:
StaticPagesControllerTest#test_should_get_about:
AbstractController::ActionNotFound: The action 'about' could not be found for StaticPagesController
    test/controllers/static_pages_controller_test.rb:16:in `block in <class:StaticPagesControllerTest>'

3 runs, 2 assertions, 0 failures, 1 errors, 0 skips

変わらずエラーとなるが「aboutアクション」が存在しないというメッセージに変わる。

static_pagesコントローラーに「aboutアクション」を追加する。

class StaticPagesController < ApplicationController
  def home
  end

  def help
  end
  
  def about
  end
end

そして、テストを再実行。

$ rails test
Running via Spring preloader in process 4434
/home/ec2-user/environment/sample_app/db/schema.rb doesn't exist yet. Run `rails db:migrate` to create it, then try again. If you do not intend to use a database, you should instead alter /home/ec2-user/environment/sample_app/config/application.rb to limit the frameworks that will be loaded.
Run options: --seed 44180

# Running:

.E.

Finished in 0.303988s, 9.8688 runs/s, 6.5792 assertions/s.

  1) Error:
StaticPagesControllerTest#test_should_get_about:
ActionController::UnknownFormat: StaticPagesController#about is missing a template for this request format and variant.

request.formats: ["text/html"]
request.variant: []

NOTE! For XHR/Ajax or API requests, this action would normally respond with 204 No Content: an empty white screen. Since you're loading it in a web browser, we assume that you expected to actually render a template, not nothing, so we're showing an error to be extra-clear. If you expect 204 No Content, carry on. That's what you'll get from an XHR or API request. Give it a shot.
    test/controllers/static_pages_controller_test.rb:16:in `block in <class:StaticPagesControllerTest>'

3 runs, 2 assertions, 0 failures, 1 errors, 0 skips

次はテンプレート(=ビュー)が存在しないというエラーになったので、ビューを追加する。

「app/views/static_pages」に「about.html.erb」というファイルを作成し、内容をRailsチュートリアルで指定されているものを記述。

<h1>About</h1>
<p>
  <a href="https://railstutorial.jp/">Ruby on Rails Tutorial</a>
  is a <a href="https://railstutorial.jp/#ebook">book</a> and
  <a href="https://railstutorial.jp/#screencast">screencast</a>
  to teach web development with
  <a href="http://rubyonrails.org/">Ruby on Rails</a>.
  This is the sample application for the tutorial.
</p>

そして、テストを実行。

$ rails test
Running via Spring preloader in process 4614
/home/ec2-user/environment/sample_app/db/schema.rb doesn't exist yet. Run `rails db:migrate` to create it, then try again. If you do not intend to use a database, you should instead alter /home/ec2-user/environment/sample_app/config/application.rb to limit the frameworks that will be loaded.
Run options: --seed 58536

# Running:

...

Finished in 0.293824s, 10.2102 runs/s, 10.2102 assertions/s.

3 runs, 3 assertions, 0 failures, 0 errors, 0 skips

やっとテスト成功。

コントローラー(アクション)を手動で作成する場合は最低限これだけのことをやる必要があるということ。

ブラウザでの動作も確認OK。

3.3.4 Refactor

これで安心してリファクタリングできるようになった。

3.4 少しだけ動的なページ

レイアウトによってページタイトルを変更するようにするが、学習しやすくするためにレイアウトファイルの名前を変えて無効化する。
(レイアウトファイルは「rails new」コマンドで「pp/views/layouts/application.html.erb」に自動的に作成されている)

$ mv app/views/layouts/application.html.erb layout_file

*普通はこのようなことはしない

3.4.1 タイトルをテストする (Red)

特定のHTMLタグが存在するかチェックする「assert_selectメソッド」を使って、各ページに「title」タグの中に「ページ名 | Ruby on Rails Tutorial Sample App」という文字が存在するかチェックするテストを追加する。

require 'test_helper'

class StaticPagesControllerTest < ActionDispatch::IntegrationTest

  test "should get home" do
    get static_pages_home_url
    assert_response :success
    assert_select "title", "Home | Ruby on Rails Tutorial Sample App"
  end

  test "should get help" do
    get static_pages_help_url
    assert_response :success
    assert_select "title", "Help | Ruby on Rails Tutorial Sample App"
  end

  test "should get about" do
    get static_pages_about_url
    assert_response :success
    assert_select "title", "About | Ruby on Rails Tutorial Sample App"
  end
end

テストを実行し、エラーとなることを確認。

$ rails test
Running via Spring preloader in process 7101
/home/ec2-user/environment/sample_app/db/schema.rb doesn't exist yet. Run `rails db:migrate` to create it, then try again. If you do not intend to use a database, you should instead alter /home/ec2-user/environment/sample_app/config/application.rb to limit the frameworks that will be loaded.
Run options: --seed 9932

# Running:

FFF

Finished in 0.179120s, 16.7485 runs/s, 33.4971 assertions/s.

  1) Failure:
StaticPagesControllerTest#test_should_get_home [/home/ec2-user/environment/sample_app/test/controllers/static_pages_controller_test.rb:7]:
Expected at least 1 element matching "title", found 0..
Expected 0 to be >= 1.

  2) Failure:
StaticPagesControllerTest#test_should_get_help [/home/ec2-user/environment/sample_app/test/controllers/static_pages_controller_test.rb:13]:
Expected at least 1 element matching "title", found 0..
Expected 0 to be >= 1.

  3) Failure:
StaticPagesControllerTest#test_should_get_about [/home/ec2-user/environment/sample_app/test/controllers/static_pages_controller_test.rb:20]:
Expected at least 1 element matching "title", found 0..
Expected 0 to be >= 1.

3 runs, 6 assertions, 3 failures, 0 errors, 0 skips

3.4.2 タイトルを追加する (Green)

各ページのビューをRailsチュートリアルでの指示通りに修正(titleタグなどを追加)する。

<!DOCTYPE html>
<html>
  <head>
    <title>Home | Ruby on Rails Tutorial Sample App</title>
  </head>
  <body>
    <h1>Sample App</h1>
    <p>
      This is the home page for the
      <a href="https://railstutorial.jp/">Ruby on Rails Tutorial</a>
      sample application.
    </p>
  </body>
</html>
<!DOCTYPE html>
<html>
  <head>
    <title>Help | Ruby on Rails Tutorial Sample App</title>
  </head>
  <body>
    <h1>Help</h1>
    <p>  Get help on the Ruby on Rails Tutorial at the
      <a href="https://railstutorial.jp/help">Rails Tutorial help
      page</a>.
      To get help on this sample app, see the
      <a href="https://railstutorial.jp/#ebook">
      <em>Ruby on Rails Tutorial</em> book</a>.
    </p>
  </body>
</html>
<!DOCTYPE html>
<html>
  <head>
    <title>About | Ruby on Rails Tutorial Sample App</title>
  </head>
  <body>
    <h1>About</h1>
    <p>
      <a href="https://railstutorial.jp/">Ruby on Rails Tutorial</a>
      is a <a href="https://railstutorial.jp/#ebook">book</a> and
      <a href="https://railstutorial.jp/#screencast">screencast</a>
      to teach web development with
      <a href="http://rubyonrails.org/">Ruby on Rails</a>.
      This is the sample application for the tutorial.
    </p>
  </body>
</html>

テストを実行し、成功することを確認する。

$ rails test
Running via Spring preloader in process 7309
/home/ec2-user/environment/sample_app/db/schema.rb doesn't exist yet. Run `rails db:migrate` to create it, then try again. If you do not intend to use a database, you should instead alter /home/ec2-user/environment/sample_app/config/application.rb to limit the frameworks that will be loaded.
Run options: --seed 51808

# Running:

...

Finished in 0.187674s, 15.9852 runs/s, 31.9704 assertions/s.

3 runs, 6 assertions, 0 failures, 0 errors, 0 skips

演習1

テストファイルの冗長的な記述(「Ruby on Rails Tutorial Sample App」)をテスト前に実行される「setupメソッド」にまとめる。

require 'test_helper'

class StaticPagesControllerTest < ActionDispatch::IntegrationTest

  def setup
    @base_title = "Ruby on Rails Tutorial Sample App"
  end

  test "should get home" do
    get static_pages_home_url
    assert_response :success
    assert_select "title", "Home | #{@base_title}"
  end

  test "should get help" do
    get static_pages_help_url
    assert_response :success
    assert_select "title", "Help | #{@base_title}"
  end

  test "should get about" do
    get static_pages_about_url
    assert_response :success
    assert_select "title", "About | #{@base_title}"
  end
end

3.4.3 レイアウトと埋め込みRuby (Refactor)

ERB(埋め込みRuby)を利用してコードを共通化する。

<% provide(:title, "Home") %>
<!DOCTYPE html>
<html>
  <head>
    <title><%= yield(:title) %> | Ruby on Rails Tutorial Sample App</title>
  </head>
  <body>
    <h1>Sample App</h1>
    <p>
      This is the home page for the
      <a href="https://railstutorial.jp/">Ruby on Rails Tutorial</a>
      sample application.
    </p>
  </body>
</html>
  • <%  %>で囲むと単に埋め込まれたRubyを実行するのみ
  • <%=  %>で囲むと埋め込まれたRubyの実行結果をHTMLに出力する
  • provideメソッドで「tilte」というシンボルに「Home」という文字列を関連つけている
  • yieldメソッドで「title」シンボルの値を出力している

テストを実行し、成功することを確認する。

$ rails test
Running via Spring preloader in process 8021
/home/ec2-user/environment/sample_app/db/schema.rb doesn't exist yet. Run `rails db:migrate` to create it, then try again. If you do not intend to use a database, you should instead alter /home/ec2-user/environment/sample_app/config/application.rb to limit the frameworks that will be loaded.
Run options: --seed 49862

# Running:

...

Finished in 0.135440s, 22.1501 runs/s, 44.3001 assertions/s.

3 runs, 6 assertions, 0 failures, 0 errors, 0 skips

同じように「help.html.erb」「about.html.erb」も修正、テストを実行し、成功することを確認する。

無効にしていたレイアウトファイルを元に戻す。

$ mv layout_file app/views/layouts/application.html.erb

「app/views/layouts/application.html.erb」をビューのHTML構造(DOCTYPE、head、bodyなど)を共通化したものなので、各ビューページの「titleタグ」部分をコピーして、各ビューファイルの内容は「bodyタグ」の中だけの内容にする。

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

  <body>
    <%= yield %>
  </body>
</html>
<% provide(:title, "Home") %>
<h1>Sample App</h1>
<p>
  This is the home page for the
  <a href="https://railstutorial.jp/">Ruby on Rails Tutorial</a>
  sample application.
</p>
  • 「bodyタグ」内の<%= yield %>は各ビューファイルの内容が入る
  • <%= csrf_meta_tags %>はWeb攻撃手法の1つであるクロスサイトリクエストフォージェリー (Cross-Site Request Forgery: CSRF)を防ぐために使われるRailsのメソッド
  • <%= stylesheet_link_tag … %>は共通のスタイルシートを読み込んでいる
  • <%= javascript_include_tag “application”, … %>は共通のJavaScriptを読み込んでいる

3.4.4 ルーティングの設定

「config/routes.rb」にてhomeページをrootに設定する。

演習1

3.4.4で設定したルーティングのテストを行う。

# 演習:FILL_INを書き換える
  test "should get root" do
    get FILL_IN
    assert_response FILL_IN
  end

# 回答
  test "should get root" do
    get root_url
    assert_response :success
  end

演習2

3.4.4のルーティングの設定を削除して、テストがエラーとなることを確認する。

Rails.application.routes.draw do
  # root 'static_pages#home'
  get 'static_pages/home'
  get 'static_pages/help'
  get 'static_pages/about'
end
$ rails test
Running via Spring preloader in process 12496
/home/ec2-user/environment/sample_app/db/schema.rb doesn't exist yet. Run `rails db:migrate` to create it, then try again. If you do not intend to use a database, you should instead alter /home/ec2-user/environment/sample_app/config/application.rb to limit the frameworks that will be loaded.
Run options: --seed 59660

# Running:

...E

Finished in 0.316704s, 12.6301 runs/s, 18.9451 assertions/s.

  1) Error:
StaticPagesControllerTest#test_should_get_root:
NameError: undefined local variable or method `root_url' for #<StaticPagesControllerTest:0x0000000004fe30b8>
    test/controllers/static_pages_controller_test.rb:10:in `block in <class:StaticPagesControllerTest>'

4 runs, 6 assertions, 0 failures, 1 errors, 0 skips

まとめ

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

ソフトウェア会社(SIer)で10年以上勤務のシステムエンジニア|ポケットWiFi使用歴2年以上|ポケットWiFi+αで快適でお得なインターネット環境を構築するための情報を発信|その他、IT情報やWebサービス、アプリ、ガジェットなどの情報を発信|自分と他の人のカバンの中身を紹介するメディア「カバンの中身ラボ(https://kaban-no-nakami-labo.com/)」も運営しています。
ポケットWiFi選びに迷ったらTwitter、お問合せフォームからご連絡ください。

コメント

コメントする

目次