Search code examples
rspectddbdd

Is there an rspec test for exact length of an attribute?


I'm trying to test the length of a zip code attribute to ensure its 5 characters long. Right now I'm testing to make sure its not blank and then too short with 4 characters and too long with 6 characters.

Is there a way to test it being exactly 5 characters? So far I've found nothing online or in the rspec book.


Solution

  • If you're testing a validation on an ActiveRecord model, I recommend trying out shoulda-matchers. It provides a bunch of useful RSpec extensions useful for Rails. You could write a simple one line spec for your zip code attribute:

    describe Address do
      it { should ensure_length_of(:zip_code).is_equal_to(5).with_message(/invalid/) }
    end