0

I have a schema:

class CreateUsers < ActiveRecord::Migration[5.2]
  def change
    create_table :users do |t|
      # Username cannot be null
      t.string :username, null: false
      t.string :password, null: false
      t.string :email, null: false
      t.integer :health_record
      t.boolean :admin, default: false
      t.boolean :activated, default: true

      t.timestamps
    end
  end
end

And I tried to run the following test:

require 'test_helper'

class UserTest < ActiveSupport::TestCase
  def setup
    @user = User.new(username: 'Bob', password: 'h1l34asi', email: 'loyu@kbu.edu')
  end

  test 'user creation' do
    assert @user.valid?
  end

  test 'user creation with no username' do
    @user.username = nil
    # This assertion won't pass!
    assert @user.invalid?
  end
end

But I always get this error:

Failure:
UserTest#test_user_creation_with_no_username [/project/test/models/user_test.rb:15]:
Expected true to be nil or false

I've tried the following before the test:

rails db:migrate
rails db:reset
rails db:migrate:reset

And my sqlite db looks fine.

But it still doesn't work. Why?

luoyianwu
  • 13
  • 1
  • 4

1 Answers1

1

null: false constraint works on DB level. You will get an error when trying to save the record in DB, but on the Model level the instance is valid despite the username is nil.

You should add validation:

class User < ApllicationRecord
  validates :username, presence: true
  # ...
end
chumakoff
  • 6,807
  • 2
  • 23
  • 45