Today I Learned

hashrocket A Hashrocket project

Test Validation Errors with RSpec

We can use RSpec unit tests to confirm model validations, like this:

# app/models/developer.rb
validates :email, format: { with: /foo/ }

# spec/models/developer_spec.rb = 'bar'
expect(developer).to_not be_valid

But there's a false positive here; expect returns true, but we can't be sure why it returned true. It may have been an invalid email, because the regex doesn't match bar, or it may be invalid for many other reasons, such as an incomplete fixture.

Another method I re-learned today is this:

# spec/models/developer_spec.rb = 'bar'
expect(developer).to_not be_valid
expect(developer.errors.message[:email]).to eq ['is invalid']

The first expect triggers the validations; the second proves the right error was included. This makes a difference when flash messages or other code depend on your errors stack.

See More #testing TILs