Validate presence of attributes using RSpec
Asked Answered
A

2

7

Some attributes in my model have presence validation and I wanted to add tests in my spec to check if an error is generated when the attribute is blank.

I'm using this code:

it 'should have a name' do
    expect(@patient.errors[:name].size).to eq(1)
end

But here is the result of the rspec command:

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
Acetal answered 6/6, 2015 at 14:18 Comment(0)
A
5

I found my mistake. I need to call @patient.valid? before checking for errors.

it 'has a name' do
    @patient.valid?
    expect(@patient.errors[:name].size).to eq(1)
end
Acetal answered 6/6, 2015 at 17:16 Comment(0)
C
6

With shoulda you can do this in one simple line:

Describe Patient do
  # original 'should' validation
  it { should validate_presence_of(:name) }

  # alternative 'expected' validation
  it { is_expected.to validate_presence_of(:name) }
end
Confocal answered 6/4, 2016 at 22:58 Comment(0)
A
5

I found my mistake. I need to call @patient.valid? before checking for errors.

it 'has a name' do
    @patient.valid?
    expect(@patient.errors[:name].size).to eq(1)
end
Acetal answered 6/6, 2015 at 17:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.