在试图将Factory Girl合并到我的项目中时,我遇到了一个我似乎无法解决的错误。我写了一个测试,将检查如果我的用户名是空的:尝试使用Factory Girl运行Rspec时测试失败
# 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当我尝试运行这个测试,我得到这个错误:
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 '
这里就是我的factories.rb
文件的样子:
# 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
如果有帮助的一切都在这里是我的Gemfile是如何设置:
group :development, :test do
gem 'rspec-rails'
gem 'rspec-collection_matchers'
gem 'factory_girl_rails'
end
更新
检查我的用户模型后,我相信,第二个错误是我错误地设置存在确认两次在我的模型:
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'}
我现在不知道是rspec的一种方式莫名其妙地指出我处理的,而不是含糊地告诉我的错误:
expected 1 errors on :first_name, got 2
所以,检查我的用户模型,我认为第二个错误是我错误地设置存在确认两次在我的模型。在我的测试中奇怪地使用'puts user.errors.messages [:first_name]'给了我和以前一样的确切错误信息。如果更正,这个答案可能会对其他用户有用。我会更新我的问题以反映它,并在修改后标记为正确。 – 2014-10-09 00:11:09