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 1 year has passed since last update.

【Rails】「<投稿内容>... 続きを見る」という部分を作る。(truncateの実装とminitestの追加)

Last updated at Posted at 2022-06-25

はじめに

記事投稿サイトでよく見る「<投稿内容>... 続きを見る」という部分を作りたい。
なので作る!!!

No 項目 内容
1 OS Mac
2 Ruby 2.6.3
3 rails 6.0.4
4 minitest 5.11.3
5 minitest-reporters 1.3.8

一覧表示テンプレートに文字数制限と"続きを見る"リンクを追加

truncateメソッドにより文字数制限をして表示する。
続きをみるはlink_toメソッドにより投稿の詳細ページ(showテンプレート)に飛ぶようにする。

app/views/microposts/index.html.erb
    <span class="content">
      <%= truncate(micropost.content, length: 100) %>
      <%#= => micropost.content.truncate(100)でも可 %>
      <% if micropost.content.size > 100 %>
        <%= link_to "続きを見る", micropost_url(micropost.id) %>
      <% end %>
    </span>

以下のような投稿の見た目になる。
スクリーンショット 2022-06-26 0.52.27.png

testスイートを書く

今回100文字制限にしているので、そこを閾値に2パターンのテストを記載する。

test/integration/interface_test.rb
  test "micropost.size is 100 over" do
    # 100文字以上の文章を投稿する
    content = "This micropost really ties the room together. 
               This micropost really ties the room together.
               This micropost really ties the room together."
    title = "title"
    assert_difference 'Micropost.count', 1 do
      post microposts_path, params: { micropost: { content: content, title: title } }
    end
    assert_redirected_to root_url
    follow_redirect!
    assert_match content.truncate(100), response.body
    assert_select 'a', "続きを見る"
  end

  test "micropost.size is 100 below" do
    # 100文字以下の文章を投稿する
    content = "This micropost really ties the room together."
    title = "title"
    assert_difference 'Micropost.count', 1 do
      post microposts_path, params: { micropost: { content: content, title: title } }
    end
    assert_redirected_to root_url
    follow_redirect!
    assert_match content.truncate(100), response.body
    assert_select 'a', "続きを見る", count: 0
  end

おわりに

案外簡単に実装できた。

参考文献

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?