ActiveModel::Errors#added?

06 Feb 22

Ever wanted to check whether a specific error has been added to an object?

Want no more.

This method in ActiveModel::Errors does exactly that. The method takes an attribute argument, and you can pass in the error type and any options too.

# activemodel/lib/active_model/errors.rb

user.errors.added? :name, :too_long, count: 25

This can be really helpful when writing tests for model validations. Since added? is a predicate method, RSpec gives us a corresponding matcher — meaning we can write more readable assertions in our tests.

--- a/user_spec.rb
+++ b/user_spec.rb


- expect(user.errors[:email]).to include "can't be blank"
+ expect(user.errors).to be_added(:email, :blank)