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チュートリアル第十四章 Relationshipのバリデーション

0
Posted at

Relationshipのバリデーション

Relationshipモデルのバリデーションをテストする

test/models/relationship_test.rb

require 'test_helper'

class RelationshipTest < ActiveSupport::TestCase

  def setup
    @relationship = Relationship.new(follower_id: users(:michael).id,
    # 新しくデータモデルからインスタンスを生成する。
    # テストユーザーidをフォロワーidにする
                                     followed_id: users(:archer).id)
                                     # テストユーザーを当てる
                                     # フォローされているidに与える
  end

  test "should be valid" do
    assert @relationship.valid?
    # インスタンスは有効か?(2項目)
  end

  test "should require a follower_id" do
    @relationship.follower_id = nil
    # follower_idを空にする
    assert_not @relationship.valid?
    # 有効ではないことを確認
  end

  test "should require a followed_id" do
    @relationship.followed_id = nil
    assert_not @relationship.valid?
  end
end

Relationshipモデルに対してバリデーションを追加する

app/models/relationship.rb

class Relationship < ApplicationRecord
  belongs_to :follower, class_name: "User"
  # belongs_to  他方のモデルのインスタンスに「従属(belongs to)」します。
  # :followerモデルはUserに従属するのか?
  
  belongs_to :followed, class_name: "User"
  # followedモデルは従属する 
  validates :follower_id, presence: true
  # 有効、存在する
  validates :followed_id, presence: true
end

Relationship用のfixtureを空にする

test/fixtures/relationships.yml

# 空にする
ubuntu:~/environment/sample_app (following-users) $ rails t
Running via Spring preloader in process 8278
Started with run options --seed 47075

  62/62: [=============================] 100% Time: 00:00:07, Time: 00:00:07

Finished in 7.40609s
62 tests, 316 assertions, 0 failures, 0 errors, 0 skips

演習

リスト 14.5のバリデーションをコメントアウトしても、テストが成功したままになっていることを確認してみましょう。(以前のRailsのバージョンでは、このバリデーションが必須でしたが、Rails 5から必須ではなくなりました。今回はフォロー機能の実装を優先しますが、この手のバリデーションが省略されている可能性があることを頭の片隅で覚えておくと良いでしょう。)

確認

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?