0

Facing a issue when i am testing this validates length with shoulda_matchers ensure_length_of

Model

class Plant < ActiveRecord::Base
  validates :code, :length => { :in => 2..6 } 
end

Rspec

require 'spec_helper'
describe Plant do

 before { @plant = FactoryGirl.create(:plant) } 
  it { should ensure_length_of(:code).is_at_least(2).with_message("is too short (minimum is 2 characters)")}
end

Error:

Failures:

  1) Plant
     Failure/Error: it { should ensure_length_of(:code).is_at_least(2).with_message("is too short (minimum is 2 characters)")}
       Did not expect errors to include "is too short (minimum is 2 characters)" when naics_code is set to "xx", got error: is too short (minimum is 2 characters)
     # ./spec/models/plant_spec.rb:11:in `block (2 levels) in <top (required)>'

Thanks!

AnkitG
  • 6,438
  • 7
  • 44
  • 72
  • i think the message should be enclosed in // rather than in quotes. it must a regex. – Prasad Surase Jun 20 '13 at 12:16
  • @prasad.surase i tried the regex way too (/your message here/). It didn't work – AnkitG Jun 20 '13 at 12:16
  • In the absence of any `subject` statement, the `it` clause is operating a `new` instance of Plant and not the FactoryGirl instance. Is that going to present problems for `shoulda` in doing its thing? Also, although I don't think it's a factor, the documentation suggests you should be using `with_too_short_message` rather than `with_message`. – Peter Alfvin Jun 23 '13 at 18:13

1 Answers1

0

As @Peter Alfvin has mentioned the problem is in subject. The Rspec implementation should look like this:

require 'spec_helper'
describe Plant do

 before { @plant = FactoryGirl.create(:plant) }
  subject { @plant } 
  it { should ensure_length_of(:code).is_at_least(2).with_message("is too short (minimum is 2 characters)")}
end
Tom Hert
  • 947
  • 2
  • 10
  • 32