Tuesday, April 17, 2012

devise認証やってみる(3/12)サイト共通レイアウト、メソッド、ビュー、ルートの追加 [rails3]


CommunityGuides 3/12 - Basic Layout, Adding Methods, Views and Routes
http://www.communityguides.eu/articles/3

サイト共通レイアウト、メソッド、ビュー、ルートの追加

ちょっとhamlを使ってみる。

gem 'haml'
% bundle install

application.html.erb を http://html2haml.heroku.com/ で変換してそのままペーストした。
application.html.erb を application.html.haml にリネーム。

app/asset/stylesheets/
http://dl.dropbox.com/u/56229/communityguides/download/communityguides.css
http://dl.dropbox.com/u/56229/communityguides/download/awesome-buttons.css
を保存。

application.html.hamlにcssリンク追加
= stylesheet_link_tag :comguide
= stylesheet_link_tag :button



トップページのview

app/views/articles/index.html.haml



app/views/articles/show.html.haml


css入れたら見た目が一気に本家と同じになる。。。



新しいルートの追加

aboutページを作ってみる

まずtest.

tests/functional/articles_controller_test.rb

test "should get about" do
  get :about
  assert_response :success
end

失敗するので、
1. route追加
2. メソッド追加
3. view作成
する。

route追加

config/routes.rb

resources :articles do
  collection do
      get 'about'
    end
end


エラー:The action 'about' could not be found
メソッド追加

(訂正:app/controllers/application_controller.rbではなく)
app/controllers/articles_controller.rb
...
before_filter :authenticate_user!, :except => [:index, :show, :about]
...
def about
end


view作成

app/views/articles/about.html.erb
%h1 About CommunityGuides

成功。




2つ目のインデックスページ作成。

トップはおすすめ記事のみにして、2つ目にはすべての記事を表示させる。

controllerにはindex.html.hamlを共有する2つのメソッドを。

いつもどおり、テストを書く>失敗する>そしてテストをパスするコードを書く、というやり方。でやれ、と。

tests/functional/articles_controller_test.rb
test "should get all articles index" do
  get :all
  assert_response :success
  assert_not_nil assigns(:articles)
end

failure!
Expected response to be a <:success>, but was <302>
が出るので、assert_response :redirect に変えたけどいいのか?(ダメです。追記参照。)

もうひとつ 1) Failure:
test_should_get_all_articles_index(ArticlesControllerTest) [/users/keepon/Desktop/Dropbox/lr3/comguide/test/functional/articles_controller_test.rb:63]:
expected to not be nil.

9 tests, 13 assertions, 1 failures, 0 errors, 0 skips

assert_not_nil assigns(:articles) の部分でnilになってるぽいけど、これはどこのことかよくわからない。article.yml とか?

---------------------
追記

原因はarticles_controller.rbのbefore_filterでした。exceptにindexとshowだけ入っている状態だったので以下のようにまとめて記述。

  before_filter :authenticate_user!, :except => [:index, :all, :show, :about]

 非ログイン時に許可されていないメソッドを呼び出していたためにredirectになっていた。assert_not_nil assigns(:articles)が評価される以前に、ログインしているかしていないかの評価のところでredirectされていた。

ログインが必要なサイトでは、ログイン状況パターンも考慮したテストでなければ、ということですね。
---------------------


ナビゲーションバーにリンク追加

= link_to "All Articles", all_articles_path
            = link_to "About", about_articles_path

おわり

No comments:

Post a Comment