railstutorial.jp 3章メモ

  • テーマ
    • rails generate
    • erb
    • 振舞駆動開発 (Behavior-Driven Development, BDD)
    • Guard

--ski-test-unit は、Test::Unitを使うのではなくRspecを使う為にtestディレクトリを作成しないオプション。

$ rails new sample_app --skip-bundle --skip-test-unit

$ bundle install --path=vendor/bundle --binstubs --without production

--without productionはremembered option。一度実行するとコマンドに保存される。

$ bundle config --delete bin
$ rake rails:update:bin

.secretを.gitignoreに追加

Rspecを使うようにRailsの設定をする

$ rails generate rspec:install
$ heroku create
$ git push heroku master
$ heroku config:set SECRET_KEY_BASE=`rake secret`
$ heroku run rake db:migrate

$ heroku restart
$ heroku open

ログが確認できる

$ heroku logs

静的ページ用のコントローラをつくる
テストは後から手動で作る為ここではつくらない

$ rails generate controller StaticPages home help --no-test-framework

underscoreメソッドを使ってキャメルケースからスネークケースに変換している
http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-underscore

rails generateはrails destroyで元に戻せる

$ rails generate controller FooBars baz quux
$ rails destroy controller FooBars baz quux

マイグレーションを戻す方法

$ rake db:migrate
$ rake db:rollback #一つ戻す
$ rake db:migrate VERSION=0 # 最初に戻す
  • アプリケーションの振る舞いをテストしながら実装する直感的手法
  • 振る舞い駆動開発(Behavior Driven Development, BDD)
  • TDDから派生
  • 結合テスト integration test (RSpecではリクエストspecと呼ぶ)
  • 単体テスト unit test

静的ページの振る舞いテストを生成

$ rails generate integration_test static_pages

spec/requests/static_pages_spec.rbが作成される

RSpec はダブルクォート (") で囲まれた文字列を無視する page変数はCapybaraが提供している

spec/spec_helper.rbにCapybara DSLを追加

RSpec.configure do |config|
  config.include Capybara::DSL
end

テスト実行

$ rspec spec/requests/static_pages_spec.rb
sample_app/spec/spec_helper.rb:93:in `block in <top (required)>': uninitialized constant Capybara (NameError)

エラー。

spec/rails_helper.rbのまねして、spec_helper.rbにも以下を書いたら動いた

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'

have_titleメソッドを使って<title>要素をチェック

Don’t Repeat Yourself, DRY原則

<% provide(:title, 'Home') %>

<%= yield(:title) %>

レイアウトファイル application.html.erb

RSpecのlet関数でテスト内変数を定義

Guardでファイル変更を感知してテストの実行を自動化する

gem 'guard-rspec’
$ bundle install
$ bundle exec guard init rspec

生成されたGuardfileにrequire追加

テストが失敗したらそこで終了する

# guard :rspec, cmd: 'bundle exec rspec' do
guard :rspec, all_after_pass: false, cmd: 'bundle exec rspec’ do


end
$ bundle exec guard

Sportを使ったテストの高速化
プリローダー。今はspringなのか?