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

I am trying to check the length of a zip code attribute to ensure it is 5 characters long. I am testing now to make sure it is not empty, and then too short with 4 characters and too long with 6 characters.

Is there any way to verify that it is exactly 5 characters? So far, I have not found anything on the Internet or in the rspec book.

+7
source share
4 answers

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

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

RSpec allows this:

 expect("this string").to have(5).characters 

In fact, you can write something instead of โ€œcharacters,โ€ it's just syntactic sugar. All that happens is that RSpec calls #length on this.

However , from your question, it sounds like you really want to check validation, in which case I would give @rossta advice.

UPDATE:

Since RSpec 3, this is no longer part of rspec's expectations, but is available as a separate stone: https://github.com/rspec/rspec-collection_matchers

+11
source

The latest major release of RSpec no longer has a match.

Like RSpec 3.1, the correct way to verify this is:

expect("Some string".length).to be(11)

+9
source

Collectors (all matches that argue against strings, hashes, and arrays) were abstracted into a separate gem, rspec-collection_matchers .

To use these mappings, add this to your Gemfile :

 gem 'rspec-collection_matchers' 

Or your .gemspec if you are working on a gem:

 spec.add_development_dependency 'rspec-collection_matchers' 

Then add this to your spec_helper.rb :

 require 'rspec/collection_matchers' 

And then you can use the assemblers in your specification:

 require spec_helper describe 'array' do subject { [1,2,3] } it { is_expected.to have(3).items } it { is_expected.to_not have(2).items } it { is_expected.to_not have(4).items } it { is_expected.to have_exactly(3).items } it { is_expected.to_not have_exactly(2).items } it { is_expected.to_not have_exactly(4).items } it { is_expected.to have_at_least(2).items } it { is_expected.to have_at_most(4).items } # deliberate failures it { is_expected.to_not have(3).items } it { is_expected.to have(2).items } it { is_expected.to have(4).items } it { is_expected.to_not have_exactly(3).items } it { is_expected.to have_exactly(2).items } it { is_expected.to have_exactly(4).items } it { is_expected.to have_at_least(4).items } it { is_expected.to have_at_most(2).items } end 

Note that you can use items and characters interchangeably, it's just sugar syntax, and the have match and its variants can be used on arrays, hashes, and your string.

0
source

All Articles