Checking for Attributes with RSpec

Some attributes in my model have a presence check and I wanted to add tests to my spec to check if an error is thrown when the attribute is empty.

I am using this code:

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

      

But here is the output from 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
+3


source to share


2 answers


I found my mistake. Do 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

      

+2


source


With shoulda, you can do it in one simple line:



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

      

+4


source







All Articles