0
votes

While trying to incorporate Factory Girl in my project I'm running into an error I just can't seem to solve. I wrote a test that would check if my user's first name was empty:

# spec/models/user_spec.rb

require 'rails_helper'

RSpec.describe User, :type => :model do
  it 'is invalid without a first name' do
    user = FactoryGirl.build(:user, first_name: nil)
    expect(user).to have(1).errors_on(:first_name)
  end
end

Unfortnately when I try to run this test I get this error:

1) User is invalid without a first name Failure/Error: expect(user).to have(1).errors_on(:first_name) expected 1 errors on :first_name, got 2 # ./spec/models/user_spec.rb:7:in `block (2 levels) in '

Here's what my factories.rb file looks like:

# spec/factories.rb

FactoryGirl.define do
  factory :user do
    first_name "John"
    last_name "Doe"
    sequence(:email) {|n| "johndoe#{n}@example.com"}
    password "secret"
  end
end

If it helps at all here's how my gemfile is setup:

group :development, :test do
  gem 'rspec-rails'
  gem 'rspec-collection_matchers'
  gem 'factory_girl_rails'
end

Update

After checking my User model I believe that the second error was me mistakenly setting the presence validation twice in my model:

validates :first_name, :last_name, :email, :password, presence: true
validates :first_name, :last_name, presence: true, format: {with: /\A([^\d\W]|[-])*\Z/, message: 'cannot have any numbers or special characters'}

What I wonder now is a way for rspec to somehow point out the errors I'm dealing with instead of vaguely telling me:

expected 1 errors on :first_name, got 2

1

1 Answers

0
votes

It seems that your user actually have 2 errors on the first_name field

To debug it you can just print the errors

RSpec.describe User, :type => :model do
  it 'is invalid without a first name' do
    user = FactoryGirl.build(:user, first_name: nil)

    puts user.errors.messages[:first_name]

    expect(user).to have(1).errors_on(:first_name)
  end
end