使用 RSpec 验证属性是否存在
Validate presence of attributes using RSpec
我的模型中的某些属性具有存在验证,我想在我的规范中添加测试以检查当属性为空时是否生成错误。
我正在使用此代码:
it 'should have a name' do
expect(@patient.errors[:name].size).to eq(1)
end
但这里是 rspec 命令的结果:
Failures:
1) Patient should have a name
Failure/Error: expect(@patient.errors[:name].size).to eq(1)
expected: 1
got: 0
(compared using ==)
# ./spec/models/patient_spec.rb:11:in `block (2 levels) in '
Finished in 0.03002 seconds (files took 40.54 seconds to load)
1 example, 1 failure
Failed examples:
rspec ./spec/models/patient_spec.rb:10 # Patient should have a name
我发现了我的错误。我需要打电话给@patient.valid?在检查错误之前。
it 'has a name' do
@patient.valid?
expect(@patient.errors[:name].size).to eq(1)
end
使用 shoulda,您只需一行即可完成此操作:
Describe Patient do
# original 'should' validation
it { should validate_presence_of(:name) }
# alternative 'expected' validation
it { is_expected.to validate_presence_of(:name) }
end
我的模型中的某些属性具有存在验证,我想在我的规范中添加测试以检查当属性为空时是否生成错误。
我正在使用此代码:
it 'should have a name' do
expect(@patient.errors[:name].size).to eq(1)
end
但这里是 rspec 命令的结果:
Failures: 1) Patient should have a name Failure/Error: expect(@patient.errors[:name].size).to eq(1) expected: 1 got: 0 (compared using ==) # ./spec/models/patient_spec.rb:11:in `block (2 levels) in ' Finished in 0.03002 seconds (files took 40.54 seconds to load) 1 example, 1 failure Failed examples: rspec ./spec/models/patient_spec.rb:10 # Patient should have a name
我发现了我的错误。我需要打电话给@patient.valid?在检查错误之前。
it 'has a name' do
@patient.valid?
expect(@patient.errors[:name].size).to eq(1)
end
使用 shoulda,您只需一行即可完成此操作:
Describe Patient do
# original 'should' validation
it { should validate_presence_of(:name) }
# alternative 'expected' validation
it { is_expected.to validate_presence_of(:name) }
end