2012-01-05 102 views
3

当我使用mongoid在rails中测试验证时遇到了问题 这是例如我的Person模型和我的Rspec测试。Rspec验证测试(Mongoid)

class Person 
    include Mongoid::Document 

    validates :first_name , :presence => true 
    validates :last_name , :presence => true 

end 



[ :last_name, :first_name ].each do |attr| 
    it "must have a #{attr}" do 
    p = Person.new 
    p.send("#{attr}=","") 
    p.should_not be_valid 
    p.errors[attr].should == [ "can't be blank" ] 
    end 
end 

但这种测试失败,因为返回值为[“不能为空”,“不能为空”]

expected: ["can't be blank"] 
     got: ["can't be blank", "can't be blank"] 

为什么在这个2级的错误记录?? 我用很多模型和其他验证规则来测试这个问题。我每次相同的结果

THX的帮助

埃里克

回答

0

这是因为你设置你的领域之一,以空字符串和其他保留的nil默认值。这就是为什么你的每次验证都会失败。

+0

但为什么我得到只有一个错误,当我在rails控制台手册()上测试这个问题.. p = Person.new p.valid? p.error [:first_name] got => [“不能为空”] – bulleric 2012-01-05 10:22:58

+0

嗯,这很有趣。 :-) – 2012-01-05 10:25:04

+0

嗯,多数民众赞成混淆......在我的控制台上我每个值只有一个错误(第一和最后一个名称)嗯,我的测试环境中可能有错误或failconfiguration ... -.- – bulleric 2012-01-05 10:38:06