windowsユーザが学ぶmacブックでのRails開発 vol.1
本章では、前章に引き続き、Railsの開発進め方について確認したいと思います。kikki.hatenablog.com
ブランチの作成
静的ページを作成する前に、ブランチを作成します。
git checkout -b static-page
※「static-page」は、ブランチ名です。
静的ページの作成
秘密鍵生成機能の作成
まず、秘密鍵(トークン)を動的生成する処理を追加します。
【config/initializers/secret_token.rb】
require 'securerandom' def secure_token token_file = Rails.root.join('.secret') if File.exist?(token_file) # Use the existing token. File.read(token_file).chomp else # Generate a new token and store it in token_file. token = SecureRandom.hex(64) File.write(token_file, token) token end end 【プロジェクト名】::Application.config.secret_key_base = secure_token
ブランチにファイルを追加
前節でのファイルをブランチに追加します。
git add config/initializers/secret_token.rb
git status
新しくファイルが追加されていることを確認できます。
静的なWebページの生成
いよいよ、静的ページを作成します。今回は、「home」と「help」ページを用意します。
rails generate controller StaticPages home help --no-test-framework
コントローラー生成時の文法は以下の通りです。
rails generate controller 【コントローラー名】 【アクション名(複数あればスペースで繋ぐ)】 【オプション】
Webページの確認
Webページの確認は、まず以下にコマンドをターミナルに入力します。
rails s
そして、ウェブブラウザから「http://localhost:3000/static_pages/home」とアクセスすると、確認できます。
テストコードの作成
テストコードを含むファイルを生成し、データベースの構造を最新化します。
rails generate integration_test static_pages
rake db:migrate
rake db:test:load
Rakeファイルの編集
またテストコードが正常に実行されるよう、「Rakefile」を編集します。
【Rakefile】
require File.expand_path('../config/application', __FILE__) require 'rake' module ::【プロジェクト名】 class Application include Rake::DSL end end module ::RakeFileUtils extend Rake::FileUtilsExt end 【プロジェクト名】::Application.load_tasks
テストファイルの編集
「Home」アクションでのテストコードを作成します。
【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 end
テストの実行
以下のコマンドをターミナルで実行すると、テストが開始されテスト結果が表示されます。
rake test test/integration/static_pages.rb
なおrailsにおけるテストライブラリについては、以下記事を参照下さい。railsguides.jp
またテストについての詳しい記事も記載しておきます。ruby.studio-kingdom.com
Gitへ変更内容を反映
最後に、今までの変更内容をGitに反映させます。
git add . git commit -m "Add Static Pages"