【发布时间】:2013-12-10 16:59:32
【问题描述】:
我将简要介绍代码示例,因为除了下面的测试之外,我的所有测试都通过了。我通过稍微改变一下让它通过了,但我不确定为什么第 1 版失败而第 2 版有效。
我的模特:
# app/models/person.rb
class Person
validates :contact_number, uniqueness: true
end
型号规格
# spec/models/person_spec.rb
require 'spec_helper'
describe Person do
it 'is a valid factory' do
create(:person).should be_valid # passes
end
it 'has a unique phone number' do
create(:person)
build(:person).should_not be_valid # fails
end
it 'also has a unique phone number' do
person1 = create(:person)
person2 = person1.dup
person2.should_not be_valid # passes
end
end
据我所知,两个唯一性测试应该做同样的事情,但是一个通过,一个失败。
如果重要的话,我正在使用 mongoid,尽管我认为这不会有任何影响。我也没有在测试中对嵌套上下文或描述做任何事情,所以我认为范围是正确的。任何见解都值得赞赏。
更新 1: 我意识到在我的工厂中我正在添加一个 initialize_with 块,如下所示:
initialize_with { Person.find_or_create_by(contact_number: contact_number) }
我意识到这可能是验证失败的原因——我只是让同一个人回来。但是,注释掉该行会出现以下错误:
Mongoid::Errors::Validations: 问题: 人员验证失败。 概括: 发现以下错误: 联系电话已被占用 解析度: 尝试使用有效数据保存文档或删除验证。
我想这在理论上是好的,因为它不会让我用相同的联系号码保存第二个人,但我希望我的测试通过。
【问题讨论】:
-
检查
person2.should_not be_valid的错误信息。该记录可能不会因其他原因而无效(换句话说,它可能会因巧合而失败)。另外,比较第二个例子中的属性,看看数字是否真的相同。 -
没有错误。那就是问题所在。应该有,但没有。同一个联系电话应该是无效的。
-
记录上肯定有错误。如果
person2.should_not be_valid通过,则说明person2.errors不能为空。 -
create(:person, contact_number: '111-111-11111') person2 = build(:person, contact_number: '111-111-1111') puts "Error are #{person2.errors. full_messages}" expect(person2).to have(1).error_on(:contact_number)....输出是 Error are [] expected 1 error on :contact_number, got 0
标签: ruby ruby-on-rails-4 factory-bot rspec-rails