2012-05-17 16 views
5

यहाँ मेरे वर्तमान वर्ग परिभाषा और कल्पना:राज्य मशीन, मॉडल सत्यापन और RSpec

class Event < ActiveRecord::Base 

    # ... 

    state_machine :initial => :not_started do 

    event :game_started do 
     transition :not_started => :in_progress 
    end 

    event :game_ended do 
     transition :in_progress => :final 
    end 

    event :game_postponed do 
     transition [:not_started, :in_progress] => :postponed 
    end 

    state :not_started, :in_progress, :postponed do 
     validate :end_time_before_final 
    end 
    end 

    def end_time_before_final 
    return if end_time.blank? 
    errors.add :end_time, "must be nil until event is final" if end_time.present? 
    end 

end 

describe Event do 
    context 'not started, in progress or postponed' do 
    describe '.end_time_before_final' do 
     ['not_started', 'in_progress', 'postponed'].each do |state| 
     it 'should not allow end_time to be present' do 
      event = Event.new(state: state, end_time: Time.now.utc) 
      event.valid? 
      event.errors[:end_time].size.should == 1 
      event.errors[:end_time].should == ['must be nil until event is final'] 
     end 
     end 
    end 
    end 
end 

जब मैं कल्पना चलाने के लिए, मैं दो विफलताओं और एक सफलता मिलती है। मुझे कोई जानकारी नहीं है की क्यों। दो राज्यों के लिए, return if end_time.blank?end_time_before_final विधि में कथन सत्य पर मूल्यांकन करता है जब यह हर बार झूठा होना चाहिए। 'स्थगित' एकमात्र ऐसा राज्य है जो पास होने लगता है। इस बारे में कोई विचार क्या हो रहा है?

+0

'before_transition: => पर: game_ended' अपूर्ण लगता है – apneadiving

+0

वस्तुओं अपने में नाकाम रहने के चश्मा में मान्य हैं? – apneadiving

+0

पहले_transition हटा दिया। दो ऑब्जेक्ट्स के लिए मान्य हैं: end_time और एक के लिए मान्य है: end_time। – keruilin

उत्तर

13

ऐसा लगता है कि आप एक चेतावनी documentation में नोट में चल रहा है:

एक महत्वपूर्ण चेतावनी है कि यहाँ, ActiveModel के सत्यापन ढांचे में एक बाधा की वजह से है, कस्टम प्रमाणकों के रूप में काम नहीं करेगा कई राज्यों में चलाने के लिए परिभाषित होने पर अपेक्षित। उदाहरण के लिए:

class Vehicle 
    include ActiveModel::Validations 

    state_machine do 
    ... 
    state :first_gear, :second_gear do 
     validate :speed_is_legal 
    end 
    end 
end 

इस मामले में,: second_gear राज्य: speed_is_legal सत्यापन के लिए ही चलाने हो जाएगी। इससे बचने के लिए, तुम इतनी तरह अपने कस्टम मान्यता को परिभाषित कर सकते हैं:

class Vehicle 
    include ActiveModel::Validations 

    state_machine do 
    ... 
    state :first_gear, :second_gear do 
     validate {|vehicle| vehicle.speed_is_legal} 
    end 
    end 
end 
+0

मीठे! पढ़ने के लिए भुगतान करता है। मुझसे ज्यादा सतर्क होने के लिए धन्यवाद। – keruilin

संबंधित मुद्दे