テスト駆動開発とは
アプリケーションを開発するときに最初にテストを作成し、次にコードを作成することです。
よく出てくるワード
・テスト駆動開発(TDD):アプリケーションの振る舞いをテスト
・振舞駆動開発(BDD):TDDから派生したテスト駆動開発方法
・結合テスト (integration test) :ユーザーがアプリケーションを使う際の一連のアクションをシミュレーションします。
・単体テスト (unit test) :メソッド単位での挙動のテスト
※Capybaraを併用すれば自然言語 (英語) に近い文法でテストを記述する事も可能。
書き方(結合テスト編)
1 テスト用ファイルを作成
$rails generate integration_test static_pages
invoke rspec
create spec/requests/static_pages_spec.rb
2 実際にテスト用ファイルにコードを記述
spec/requests/static_pages_spec.rb
require 'spec_helper'
describe "Static pages" do #""内は好きな文字列でOK / 読み手にとってわかりやすい文字列で!
describe "Home page" do #/statc_pages/homeのテスト
it "should have the content 'Sample App'" do
visit '/static_pages/home'
expect(page).to have_content('Sample App')
end
end
end
・it "…" do
:テスト例を記述
・visit
:Capybaraが用意している機能の一つ。/static_pages/homeへのアクセスをシミュレーションしてくれる。
・expect(page)
:Capybaraが提供するpage変数を使って、アクセスした結果のページに正しいコンテンツが表示されているかどうかをテストしてくれる。
3 spec_helper.rbにCapybara DSLを追加
spec/spec_helper.rb
RSpec.configure do |config|
.
.
.
config.include Capybara::DSL
end
4 実行
bundle exec rspec spec/requests/static_pages_spec.rb
5 テストするページを追加
spec/requests/static_pages_spec.rb
require 'spec_helper'
describe "Static pages" do
describe "Home page" do #/statc_pages/homeのテスト
it "should have the content 'Sample App'" do
visit '/static_pages/home'
expect(page).to have_content('Sample App')
end
end
describe "Help page" do #(追加)/statc_pages/helpのテスト
it "should have the content 'Help'" do
visit '/static_pages/help'
expect(page).to have_content('Help')
end
end
end