exerq
exerq

Reputation: 125

Rspec validates length

I'm learning rspec, I try to valitade length of my model, but I have this errors and I don't know what is going wrong?

 #factories/user
 FactoryGirl.define do
  factory :user do
   first_name {"Name"}
   last_name {"Surename"}
   phone_number {"1245767"}
   email {"[email protected]"}
   password {"password"}
  end
 end

user_spec: it { should validate_length_of(:phone_number).is_at_least(7)}

user model: validates_length_of :phone_number, minimum: 7

error:

 User validations should ensure phone_number has a length of at least 7
 Failure/Error: it { should validate_length_of(:phone_number).is_at_least(7)}
   Did not expect errors to include "is too short (minimum is 7 characters)" when phone_number is set to "xxxxxxx",
   got errors:
   * "can't be blank" (attribute: email, value: "")
   * "can't be blank" (attribute: password, value: nil)
   * "is too short (minimum is 7 characters)" (attribute: phone_number, value: 0)
   * "can't be blank" (attribute: first_name, value: nil)
   * "can't be blank" (attribute: last_name, value: nil)

thank you

@edit

 require 'rails_helper'

describe User do 
 describe 'validations' do
    it { should validate_presence_of :first_name }
    it { should validate_presence_of :last_name }
    it { should validate_presence_of :phone_number }
    it { should validate_length_of(:phone_number).is_at_least(7)}
 end
end

Upvotes: 1

Views: 2057

Answers (1)

zetetic
zetetic

Reputation: 47548

When using an implicit subject, RSpec instantiates the class for you, e.g.:

describe User
  it { should_blah_blah }
end

At this point the subject (meaning the thing referred to by it) is an instance of User created by calling User.new. This is convenient for some unit tests, but in your case you want to initialize the user with a factory. Use the explicit subject, e.g.:

describe User
  subject { build(:user) }
  it { should_blah_blah }
end

Now the subject is a User instance initialized from the factory definition.

More info in the RSpec docs

Upvotes: 1

Related Questions