RailsでWebさーびす作ってみる-3日目-


やっとこ3日目、果たしてリリースできるのかー!

トップページだけでも見れるようにしましょ。

最初はてすと書く

TDDだとテスト書いてからコード書くよーなのです。

spork 動かさないともっさりすぎるので起動。

$ spork

トップページとかのコントローラは PagesController にする。

$ rails g controller Pages home

PagesController のテストも自動で作られちゃっててステキ。

spec/controllers/pages_controller_spec.rb

require 'spec_helper'

describe PagesController do

  describe "GET 'home'" do
    it "should be successful" do
      get :home
      response.should be_success
    end
  end

end

てすとさーば動かしてテストしてみる。

$ rails server
$ rspec spec/controllers/pages_controller_spec.rb

PagesController
GET 'home'
. should be successful


Finished in 0.92794 seconds
1 example, 0 failures

Finished in 0.92794 seconds
1 example, 0 failures

よさそうだねー。
config/routes.rb にデフォルトページを追加しとく。

root :to => "pages#home"

おkおk。

TDDぽくテスト書いてトップのデザインやってみよ。

タイトルのテスト付け足して。

# encoding: utf-8

require 'spec_helper'

describe PagesController do
  render_views

  describe "GET 'home'" do
    before do
      get 'home'
    end

    it "should be successful" do
      response.should be_success
    end

    it "should have the title" do
      response.should have_selector("title", :content => "Alcapa")
    end
  end
end

複数のテストで共通の初期処理なんかは before に入れとくんだね。

てすとしよー。

$ rspec spec/controllers/pages_controller_spec.rb

もち失敗。

Failures:

1) PagesController GET 'home' should have the title
Failure/Error: response.should have_selector("title", :content => "Alcapa")
expected following output to contain a Alcapa tag:

てすとが通るよーに実装

トップページがんがる。

開発の順番ちょーてきとー。

タイトルの設定の仕方が Rails3 ではちょと変わったみたい。

app/views/layouts/application.html.erb

Rails 2 だと

<%= yield(:title) || 'Alcapa' %>

Rails 3 だとこんな感じ。

<%= content_for?(:title) ? yield(:title) : 'Alcapa' %>

ビューの方はこんなん。

<% content_for :title do -%>Alcapa<% end -%>

テンプレに埋め込む値をそれぞれのビューの方で設定してやるんだねー。

URL考えてみる

トップも見れるようになったし、URL考えてみる。

Rails3 だと RESTful なアプリがオススメされてるぽいので、それっぽく。

募集する方 -> recruiter
お仕事 -> offer

Gemfile はこんな感じ?

root :to => "pages#home"

resource :recruiter do
  resources :offers
end

match '/home', :to => 'pages#home'

REST で認証ってよくわからないねー。

セッションで状態管理すること止めないといけないんかな?

まー今回はセッション管理を捨てない方向で。

ルーティングを見てみる。

$ rake routes

うん、それっぽいネ!

次はいよいよ機能を実装してきましょー!