テストを書く(単純編)
前回からの続きです。
ようやく本題です。まずは、index画面を表示させるテストを書くことにします。
require 'spec_helper' describe "Tasks" do describe "GET /tasks" do it "displays tasks" do Task.create!(:name => "foobar") visit tasks_path page.should have_content("foobar") end end end
テストを実行しましょう。
tsubame.local{miyohide}% rake spec:requests /Users/miyohide/.rvm/rubies/ruby-1.9.2-p290/bin/ruby -S rspec ./spec/requests/task_spec.rb . Finished in 0.57346 seconds 1 example, 0 failures tsubame.local{miyohide}%
見事成功です。
やっていることは単純で、
Task.create!(:name => "foobar")
で事前にデータを作っておいて、
visit tasks_path
で目的のページにアクセスしたら、
page.should have_content("foobar")
ページにさっき作ったデータが表示されていることを確認できるってことをやってます。
ちょっと複雑なテスト
一覧画面を表示するだけは流石にツマラナイので、新しくタスクを作成することをやってみます。
spec/requests/task_spec.rbに次を追加します。
describe "POST /tasks" do it "create a task" do visit new_task_path fill_in "Name", :with => "hogehoge" click_button "Create Task" page.should have_content("successfully") page.should have_content("hogehoge") end end
ものから追加されたものを述べると、
fill_in "Name", :with => "hogehoge"
では、ラベル名「Name」に紐づくフィールドに値「hogehoge」を挿入するということをやっています。
fill_inには、ラベル名のほかに、フィールドのID値でもOKなので、
fill_in "task_name", :with => "hogehoge"
としてもOK。
後は、
click_button "Create Task"
で、"Create Task"というvalue値を持つボタンをクリック。後は、have_contentでデータが含まれているかどうかチェックしているだけですね。
画面を保存する
Webアプリなので、Web画面を保存したいですよね。これも簡単で、先程のプログラムに、save_pageと書けばOK。例えば、ボタンクリックした後の画面を保存したかったら、
describe "POST /tasks" do it "create a task" do visit new_task_path fill_in "task_name", :with => "hogehoge" click_button "Create Task" save_page page.should have_content("successfully") page.should have_content("hogehoge") end end
と書けばOK。ファイルは、tmp/capybara/capybara-日付+時刻+なんか数字+.htmlといった感じで出力されます。