user3574603
user3574603

Reputation: 3618

Rails tutorial test passing despite validations not being yet implemented

I'm following Michael Hartl's Rails tutorial (https://www.railstutorial.org/book/following_users#code-relationship_validations) and I'm trying to understand why a test that I thought should fail is passing.

I have a Relationship model. It looks like this:

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

I have added the following test:

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

The relevant part in schema.rb looks like this:

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

Despite having commented out the validations, the test still passes. As I understand it, the final two assertions should fail as there are no validations to prevent either column being set to nil. Why do they pass without the validations? Is it because there's an index on both columns?

Upvotes: 0

Views: 43

Answers (1)

Simple Lime
Simple Lime

Reputation: 11035

In rails 5, the belongs_to association is required by default, you can set the :optional option for it to true, but it's default is false.

I believe this tutorial has been around for years (I know a Michael Hartl rails tutorial has been around for a while, I'd assume it's this same one), though it looks like it's been updated for at least rails 5.1.4. When updating things like this to newer versions, sometimes things get missed, and I'd assume they just missed this reference, or didn't realize belongs_to had changed (it used to be optional by default and you had to have the validations there). It's also very likely they just updated the rails version and reran the tests and saw everything was still passing.

Upvotes: 1

Related Questions