ぞえの技術めも

Ruby on Rails勉強中

【145日目】【1日20分のRailsチュートリアル】【第11章】Micropostモデルのバリデーション

Ruby on Railsチュートリアル(第3版)

今日は「11.1.2 Micropostのバリデーション」から。

11.1.2 Micropostのバリデーション

Micropostの初期テストはUserモデルの初期テスト (リスト6.7) と似ています。

まずはMicropostモデル単体のテストを作成する。

test/models/micropost_test.rb

require 'test_helper'

class MicropostTest < ActiveSupport::TestCase

  def setup
    @user = users(:michael)
    # 次の行は慣習的に間違っている
    @micropost = Micropost.new(content: "Lorem ipsum", user_id: @user.id)
  end

  test "should be valid" do
    assert @micropost.valid?
  end

  test "user id should be present" do
    @micropost.user_id = nil
    assert_not @micropost.valid?
  end
end

慣習的に間違っているコードは後で修正するそう。

また、有効性に対するテストは成功しますが、存在性に対するテストは失敗するはずです。これは、Micropostモデルのバリデーションがまだ何もないことが原因です。

"test_user_id_should_be_present"のテストで失敗しますね。

$ bundle exec rake test:models
 FAIL["test_user_id_should_be_present", MicropostTest, 2017-05-26 15:23:17 +0000]
 test_user_id_should_be_present#MicropostTest (1495812197.48s)
        Expected true to be nil or false
        test/models/micropost_test.rb:17:in `block in <class:MicropostTest>'

14 tests, 23 assertions, 1 failures, 0 errors, 0 skips

これを修正するためには、ユーザーidに対するバリデーションを追加する必要があります (リスト11.4)。

Micropostモデルにバリデーションを追加。

app/models/micropost.rb

class Micropost < ActiveRecord::Base
  belongs_to :user
  validates :user_id, presence: true
end

これでテストが通るようになりました。

$ bundle exec rake test:models
14 tests, 23 assertions, 0 failures, 0 errors, 0 skips

user_id属性と同様に、content属性も存在する必要があり、さらにマイクロポストが140文字より長くならないよう制限を加えます。

content属性とマイクロポストの制限に関するテストを追加。

test/models/micropost_test.rb

  test "content should be present" do
    @micropost.content = "   "
    assert_not @micropost.valid?
  end

  test "content should be at most 140 characters" do
    @micropost.content = "a" * 141
    assert_not @micropost.valid?
  end

バリデーション追加してないのでテストは失敗する。

$ bundle exec rake test:models
 FAIL["test_content_should_be_at_most_140_characters", MicropostTest, 2017-05-26 15:23:17 +0000]
 test_content_should_be_at_most_140_characters#MicropostTest (1495812197.13s)
        Expected true to be nil or false
        test/models/micropost_test.rb:27:in `block in <class:MicropostTest>'

 FAIL["test_content_should_be_present", MicropostTest, 2017-05-26 15:23:17 +0000]
 test_content_should_be_present#MicropostTest (1495812197.13s)
        Expected true to be nil or false
        test/models/micropost_test.rb:22:in `block in <class:MicropostTest>'
16 tests, 25 assertions, 2 failures, 0 errors, 0 skips

これに対応するアプリケーション側の実装は、Userのname用バリデーション (リスト6.16) と全く同じです。

Userモデルと同じようなバリデーションをMicropostモデルに追加。

app/models/micropost.rb

  validates :content, presence: true, length: { maximum: 140 }

これでテストは通るようになりました。

$ bundle exec rake test:models
16 tests, 25 assertions, 0 failures, 0 errors, 0 skips

今日の学習時間は【18分】

次は「11.1.3 User/Micropostの関連付け」から。