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.
RSpec is a testing tool for Ruby, created for behavior-driven development (BDD). It is the most frequently used testing library for Ruby in production applications. Even though it has a very rich and powerful DSL (domain-specific language), at its core it is a simple tool which you can start using rather quickly.
RSpec is a unit test framework for the Ruby programming language. RSpec is different than traditional xUnit frameworks like JUnit because RSpec is a Behavior driven development tool.
The word it is another RSpec keyword which is used to define an “Example”. An example is basically a test or a test case. Again, like describe and context, it accepts both class name and string arguments and should be used with a block argument, designated with do/end.
There is no more have
matcher in the latest major release of RSpec.
As of RSpec 3.1, the correct way to test this is :
expect("Some string".length).to be(11)
RSpec allows this:
expect("this string").to have(5).characters
You can actually write anything instead of 'characters', it's just syntactic sugar. All that's happening is that RSpec is calling #length
on the subject.
However, from your question it sounds like you actually want to test the validation, in which case I would folow @rossta's advice.
UPDATE:
Since RSpec 3, this is no longer part of rspec-expectations, but is available as a separate gem: https://github.com/rspec/rspec-collection_matchers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With