代码之家  ›  专栏  ›  技术社区  ›  user3574603

尽管尚未实现验证,但Rails教程测试仍通过

  •  0
  • user3574603  · 技术社区  · 7 年前

    我在听迈克尔·哈特尔的轨道教程( https://www.railstutorial.org/book/following_users#code-relationship_validations )我试图理解为什么我认为应该失败的测试通过了。

    我有一个 Relationship 模型。看起来是这样的:

    class Relationship < ApplicationRecord
        belongs_to :follower, class_name: "User"
        belongs_to :followed, class_name: "User"
        # validates :follower_id, presence: true
        # validates :followed_id, presence: true
    end
    

    我添加了以下测试:

    require 'test_helper'
    
    class RelationshipTest < ActiveSupport::TestCase
    
      def setup
        @relationship = Relationship.new(follower_id: users(:michael).id,
                                         followed_id: users(:archer).id)
      end
    
      test "should be valid" do
        assert @relationship.valid?
      end
    
      test "should require a follower_id" do
        @relationship.follower_id = nil
        assert_not @relationship.valid?
      end
    
      test "should require a followed_id" do
        @relationship.followed_id = nil
        assert_not @relationship.valid?
      end
    end
    

    相关部分 schema.rb 如下所示:

    create_table "relationships", force: :cascade do |t|
      t.integer "follower_id"
      t.integer "followed_id"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
      t.index ["followed_id"], name: "index_relationships_on_followed_id"
      t.index ["follower_id", "followed_id"], name: "index_relationships_on_follower_id_and_followed_id", unique: true
      t.index ["follower_id"], name: "index_relationships_on_follower_id"
    end
    

    尽管已经对验证进行了注释,但测试仍然通过。据我所知,最后两个断言应该失败,因为没有任何验证可以防止将任一列设置为零。为什么没有验证就通过了?是因为两列都有索引吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Simple Lime    7 年前

    在Rails 5中, belongs_to 默认情况下需要关联,您可以设置 :optional 选项为“真”,但默认值为“假”。

    我相信这个教程已经存在多年了(我知道 MichaelHartlRails教程已经存在一段时间了,我假设它是同一个教程),尽管看起来它至少已经针对Rails 5.1.4进行了更新。当把类似这样的东西更新到新版本时,有时会错过一些东西,我假设它们只是错过了这个引用,或者没有意识到 属于 已经更改(默认情况下它是可选的,您必须在那里进行验证)。他们很可能只是更新了Rails版本,重新运行了测试,结果发现一切都还通过了。