我正在学习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
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
答案 0 :(得分:1)
当使用隐式主题时,RSpec会为您实例化该类,例如:
describe User
it { should_blah_blah }
end
此时主题(意为it
引用的内容)是通过调用User
创建的User.new
实例。这对于某些单元测试很方便,但在您的情况下,您希望使用工厂初始化用户。使用明确的主题,例如:
describe User
subject { build(:user) }
it { should_blah_blah }
end
现在主题是从工厂定义初始化的User
实例。