首页 文章

使用RSpec验证属性的存在

提问于
浏览
4

我的模型中的某些属性具有在线验证,我想在我的规范中添加测试,以检查属性为空时是否生成错误 .

我正在使用此代码:

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

2 回答

  • 3

    我发现了自己的错误 . 我需要打电话给@ patient.valid吗?在检查错误之前 .

    it 'has a name' do
        @patient.valid?
        expect(@patient.errors[:name].size).to eq(1)
    end
    
  • 4

    使用shoulda,您可以在一个简单的行中执行此操作:

    Describe Patient do
      it { should validate_presence_of(:name) }
    end
    

相关问题