Search code examples
ruby-on-railsruby-on-rails-3rspecrspec2rspec-rails

Check if attribute contains 2 letters in RSpec


What is the right way to test if the field contains 2 letter string with RSpec ? I am following an old example that I guess worked in rails 2. It creates new Address instance, sets invalid value on it, and then trigger valid? on that instance and finally checks if the errors report something wrong.

  it 'requires state to be of length 2' do
      subject = Address.new
      subject.state = 'Cal'
      should_not be_valid
      subject.errors.on(:state).should_not be_nil
    end

Now, Rails 3 doesn't have errors.on, so I tried with

subject.errors[:state].should_not be_nil

But the problem here is that errors[:attribute] is empty Array instead of nil.


Solution

  • You can still say

    subject.errors[:state].should_not be_empty