2015-10-13 89 views
1

我在学习rspec,我尝试调整模型的长度,但是我有这个错误,我不知道错在哪里?Rspec验证长度

#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)}

用户模型:validates_length_of :phone_number, minimum: 7

错误:

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) 

谢谢

@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 
+1

你能发布你的全部规格吗?它在我看来你并没有创建一个用户对象。通过做'user = build(:user)'之类的东西。 – userFriendly

+0

看看你的db/schema.rb文件。如果'users'上的':phone_number'列的类型是':integer',那么这可能是罪魁祸首。在这种情况下,请尝试将列的类型更改为':string'。 (我建议这样做的理由:'“xxxxxxx”.to_i == 0') – Raffael

回答

1

当使用隐式主题,RSpec的实例为您的类,例如:

describe User 
    it { should_blah_blah } 
end 

此时的主题(这意味着通过it提到的东西)是通过调用User.new创建的User一个实例。这对于某些单元测试很方便,但在你的情况下你想用工厂初始化用户。使用明确的主题,例如:

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

现在的主题是User例如从工厂定义初始化。

更多的信息在RSpec docs