Only Bolivian Here
Only Bolivian Here

Reputation: 36733

Rails model failing test assertion

Here's my Model code:

class User < ActiveRecord::Base  

  validates :email, :presence => true,
                  :uniqueness => true,
                  :format => {
                    :with => %r{^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$},
                    :message => "You must enter a valid email address."
                  }

  validates :password, :presence => true,
                       :confirmation => true,
                       :length => { :in => 6..20 }

  validates :password_confirmation, :presence => true

  validates :firstname, :presence => true

  validates :lastname, :presence => true

end

And my test:

require 'test_helper'

class UserTest < ActiveSupport::TestCase

  test "user email must not be empty" do
    user = User.new
    assert user.invalid?
    assert user.errors[:email].any?
  end

  test "user password must be between 6 and 20 characters" do
    user = User.new(:email => "[email protected]",
                    :firstname => "sergio",
                    :lastname => "tapia")

    user.password = "123"
    assert user.invalid?

    user.password = ""
    assert user.invalid?

    #6 characters.
    user.password = "123456"
    assert user.valid?

    #20 characters.
    user.password = "12345678901234567890"
    assert user.valid?

    #21 characters.
    user.password = "123456789012345678901"
    assert user.invalid?

  end

end

And the result of the tests:

sergio@sergio-VirtualBox:~/code/ManjarDeOro$ rake test:units
Run options: 

# Running tests:

.F

Finished tests in 0.105599s, 18.9395 tests/s, 47.3488 assertions/s.

  1) Failure:
test_user_password_must_be_between_6_and_20_characters(UserTest) [/home/sergio/code/ManjarDeOro/test/unit/user_test.rb:24]:
Failed assertion, no message given.

2 tests, 5 assertions, 1 failures, 0 errors, 0 skips

So the assertion fails on this bit:

#6 characters.
user.password = "123456"
assert user.valid?

So what is going on? Is my conditional for the assertion incorrect? I thought a 6 character password would turn my "user" object to .valid.

I'm new to Rails.

Upvotes: 1

Views: 3390

Answers (1)

yoavmatchulsky
yoavmatchulsky

Reputation: 2960

Your user wasn't validated because you missed the password_confirmation part of the user.

user.password = "123456"
user.password_confirmation = "123456"
assert user.valid?

Upvotes: 4

Related Questions