Ruby on rails Rspec验证长度
我正在学习rspec,我试图验证我的模型的长度,但我有这个错误,我不知道出了什么问题Ruby on rails Rspec验证长度,ruby-on-rails,rspec,Ruby On Rails,Rspec,我正在学习rspec,我试图验证我的模型的长度,但我有这个错误,我不知道出了什么问题 #factories/user FactoryGirl.define do factory :user do first_name {"Name"} last_name {"Surename"} phone_number {"1245767"} email {"email@email.net"} password {"password"} end end 用户规格:
#factories/user
FactoryGirl.define do
factory :user do
first_name {"Name"}
last_name {"Surename"}
phone_number {"1245767"}
email {"email@email.net"}
password {"password"}
end
end
用户规格:it{应该验证(:电话号码)的长度。{u至少是(7)}
用户型号:验证的长度为:电话号码,最小为: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)
多谢各位
@编辑
使用隐式主题时,RSpec会为您实例化类,例如:
describe User
it { should_blah_blah }
end
此时,主题(指由it
引用的事物)是通过调用User.new
创建的User
的实例。这对于某些单元测试很方便,但在您的情况下,您希望使用工厂初始化用户。使用明确的主题,例如:
describe User
subject { build(:user) }
it { should_blah_blah }
end
现在,主题是从工厂定义初始化的用户
实例
更多信息请参见你能发布你的全部规格吗?在我看来,您并没有创建用户对象。通过执行类似于
user=build(:user)
的操作,查看您的db/schema.rb文件。如果用户
上的:phone_number
列的类型为:integer
,则这可能是罪魁祸首。在这种情况下,请尝试将列的类型更改为:string
。(我建议这样做的原因:“xxxxxxx”。to_I==0
)
describe User
subject { build(:user) }
it { should_blah_blah }
end