cucumberを使ってみる

インストールはhttp://wiki.github.com/aslakhellesoy/cucumber/ruby-on-railsを参考に

gem install rspec rspec-rails cucumber webrat

プロジェクト内にcucumber用のフォルダを生成する

ruby script/generate cucumber

テストしたい機能のテスト用ファイルを生成

ruby script/generate feature User

具体的にどうテストを書いていくかというと、

  • テストシナリオをプレーンテキストで書く
  • テキストに対応するコード(ステップと呼ぶ?)を記述する

シナリオは例えばこう(manage_users.feature)

Feature: Manage User
  In order to [goal]
  [stakeholder]
  wants [behaviour]

  Scenario: cannot login
	Given I am on the login page
	When I fill in "メールアドレス" with "ng@example.com"
	When I fill in "パスワード" with "hogehoge"
	And I press "ログイン"
	Then I should see "ID/パスワードの組み合わせが無効です"

  Scenario: login 
	Given I am on the login page
	When I fill in "メールアドレス" with "ok@example.com"
	When I fill in "パスワード" with "hogehoge"
	And I press "ログイン"
	Then I should see "ようこそほげほげさん"

これに対応するステップファイルはこんな感じ(designer_steps.rb)

Given /^on the designer login page/ do
  visit "login/designer"
end

シナリオ中の[Given I am on the login page]に対応して[visit "login/designer"]が呼ばれる感じその他、fill inとかI pressについては、webrat_setps.rbに記述がある。

When /^I press "([^\"]*)"$/ do |button|
  click_button(button)
end
・・・
When /^I fill in "([^\"]*)" with "([^\"]*)"$/ do |field, value|
  fill_in(field, :with => value) 
end

fill_inの第一引数でフィールドを指定する方法はid属性かlabelタグを使う。webratが素敵な感じにブラウザに対する操作をラップしてくれて良い。
fixturesを読み込みたいときは「fixtures/support/env.rb」に以下を記述。
(参考:http://wiki.github.com/aslakhellesoy/cucumber/fixtures

#Seed the DB
Fixtures.reset_cache  
fixtures_folder = File.join(RAILS_ROOT, 'spec', 'fixtures')
fixtures = Dir[File.join(fixtures_folder, '*.yml')].map {|f| File.basename(f, '.yml') }
Fixtures.create_fixtures(fixtures_folder, fixtures)

かなりユーザーに近い視点でテストできて良い感じです。