0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

railsチュートリアル第10章 パーシャルのリファクタリング

Posted at

###パーシャルのリファクタリング
railsの便利なツールを使ってコードを整理する

####indexビューに対する最初のリファクタリング
app/views/users/index.html.erb

<% provide(:title, 'All users') %>
<h1>All users</h1>

<%= will_paginate %>

<ul class="users">
  <% @users.each do |user| %>
    <%= render user %>
  <% end %>
</ul>

<%= will_paginate %>

####各ユーザーを表示するパーシャル
app/views/users/_user.html.erb

<li>
  <%= gravatar_for user, size: 50 %>
  <%= link_to user.name, user %>
</li>

####indexページの完全なリファクタリング
app/views/users/index.html.erb

<% provide(:title, 'All users') %>
<h1>All users</h1>

<%= will_paginate %>

<ul class="users">
    <%= render @users %>>
     <!--Railsは@users をUserオブジェクトのリストであると推測-->
    <!--ユーザーのコレクションを与えて呼び出すと、
          Railsは自動的にユーザーのコレクションを列挙し、
          それぞれのユーザーを_user.html.erbパーシャルで出力します。-->
</ul>

<%= will_paginate %>

#####テスト

ubuntu:~/environment/sample_app (updating-users) $ rails t
Running via Spring preloader in process 13391
Started with run options --seed 44048

  39/39: [============================] 100% Time: 00:00:03, Time: 00:00:03

Finished in 3.78213s
39 tests, 131 assertions, 0 failures, 0 errors, 0 skips

###演習
1.
リスト 10.52にあるrenderの行をコメントアウトし、テストの結果が red に変わることを確認してみましょう。

ubuntu:~/environment/sample_app (updating-users) $ rails t
Running via Spring preloader in process 13535
Started with run options --seed 33825

 FAIL["test_index_including_pagination", #<Minitest::Reporters::Suite:0x0000563856c5da48 @name="UsersIndexTest">, 2.744917383000029]
 test_index_including_pagination#UsersIndexTest (2.74s)
        Expected at least 1 element matching "a[href="/users/14035331"]", found 0..
        Expected 0 to be >= 1.
        test/integration/users_index_test.rb:19:in `block (2 levels) in <class:UsersIndexTest>'
        test/integration/users_index_test.rb:18:in `block in <class:UsersIndexTest>'

  39/39: [============================] 100% Time: 00:00:03, Time: 00:00:03

Finished in 3.65557s
39 tests, 102 assertions, 1 failures, 0 errors, 0 skips
Expected at least 1 element matching "a[href="/users/14035331"]", found 0..
        Expected 0 to be >= 1.```
1以上の方がいいらしい。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?