0

I am trying to write a validation test for the name attribute in order to check if its present. My user_test.rb file:

require 'test_helper'

class UserTest < ActiveSupport::TestCase

  def setup
    @user = User.new(name: "Example User", email: "user@example.com")
  end

  test "should be valid" do
    assert @user.valid?
  end

  test "name should be present" do
    @user.name = " "
    assert_not @user.valid?
  end

end

My user.rb file:

class User < ActiveRecord::Base
  validates(:name, presence: true)
end

My I/O in the console when testing:

2.2.1 :007 > user = User.new(name: "", email: "ex@example.com")
 => #<User id: nil, name: "", email: "ex@example.com", created_at: nil, updated_at: nil> 
2.2.1 :008 > user.valid?
 => true 

2 Answers2

3

You are not getting error, because it is not nil. Understand the difference between nil and blank here

You need to provide validation like this to avoid having blank values:

validates :name, presence: true, allow_blank: false

Hope it helps!

Community
  • 1
  • 1
Dusht
  • 4,712
  • 3
  • 18
  • 24
1

The problem is, that presence: true validate if the attribute is not nil. You need to use allow_blank to validate if a string is empty or not.

validates :name, presence: true, allow_blank: false

Check out the API documentation about this topic.

Robin
  • 8,162
  • 7
  • 56
  • 101