Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

tdd

rspec

bdd

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.

like image 970
gr0k Avatar asked Apr 19 '13 21:04

gr0k


People also ask

What is an RSpec test?

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.

Is RSpec used for unit testing?

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.

What is an example in RSpec?

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.


2 Answers

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)

like image 55
Pak Avatar answered Sep 19 '22 01:09

Pak


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

like image 25
Andy Waite Avatar answered Sep 19 '22 01:09

Andy Waite