测试使用ensure_length_of shoulda匹配器验证长度

时间:2013-06-20 12:12:57

标签: ruby ruby-on-rails-3 rspec shoulda

当我使用shoulda_matchers ensure_length_of测试此验证长度时遇到问题

模型

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

错误:

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)>'

谢谢!

1 个答案:

答案 0 :(得分:0)

正如@Peter Alfvin所提到的,问题在于主题。 Rspec实现应该如下所示:

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