我在听迈克尔·哈特尔的轨道教程(
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
尽管已经对验证进行了注释,但测试仍然通过。据我所知,最后两个断言应该失败,因为没有任何验证可以防止将任一列设置为零。为什么没有验证就通过了?是因为两列都有索引吗?