2013-06-20 34 views
0

面對,當我測試此驗證與shoulda_matchers ensure_length_of測試驗證長度使用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)>' 

謝謝!

+0

我認爲這個消息應該用//而不是用引號引起來。它必須是一個正則表達式。 –

+0

@ prasad.surase我也嘗試過正則表達式(/你的消息在這裏/)。它不起作用 – AnkitG

+0

在沒有任何'subject'語句的情況下,'it'子句正在操作Plant的'new'實例,而不是FactoryGirl實例。這是否會給'shoulda'造成問題?另外,雖然我不認爲這是一個因素,但文檔建議您應該使用'with_too_short_message'而不是'with_message'。 –

回答

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