2015-10-13 114 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