2012-02-16 137 views
1

我有以下的對象和關係,防止狀態耦合?

Lecture >- Tests 
Test >- Questions 

業務規則

When the lecture is started, a test can be given 
If a test is being given, questions can be asked 

推理

Therefore questions shouldn't be asked if the lecture hasn't been started. 

問題型號

class Question 
    belongs_to :test 
    belongs_to :lecture, :through => :test 

    def ask_question 
    raise "Test not started!" unless test.started? 
    raise "Lecture not started!" unless lecture.started? 
    end 
end 

顯然,問題模型的狀態現在與測試和課堂狀態相結合。

當創建單元測試時,爲了測試這個,我需要設置所有這個狀態,這很難實現,特別是當業務案例變得越來越複雜時。

我該如何避免這種情況?

回答

2

我沒有使用Ruby關聯,但在我看來,不知何故數據模型與運行時邏輯共同在這裏。

如果我爲問題和測試建立數據模型,我想在測試中重複使用我的問題,並在講座中重複使用準備好的測試(問題集)。在這種情況下,我會寫從結構類似

class Lecture 
    has_and_belongs_to_many :tests 
end 

class Test 
    has_and_belongs_to_many :lectures 
    has_and_belongs_to_many :questions 
end 

class Question 
    has_and_belongs_to_many :tests 
end 

另外我不得不與實時講座,測試,問題和結果的概念有些結構。結果是試圖回答給定學生的實時問題。

我也「委託」講座會話狀態的檢查到測試會話。如果因爲任何原因無法啓動測試會話,則問題會話無法啓動。

要單元測試問題會話,您只需要模擬測試會話,單元測試您需要模擬演講會話的測試會話等等。

class Lecture_Session 
    has_many :tests_sessions 
    belongs_to :lecture 
end 

class Test_Session 
    belongs_to :lecture_session 
    belongs_to :test 
    has_many :question_sessions 

    def validate 
    raise "Lecture not started!" unless lecture_session.started? 
    end 
end 

class Question_Session 
    belongs_to :question 
    belongs_to :test_session 

    def validate 
    raise "Test not started!" unless test_session.started? 
    end 
end 

class Result 
    belongs_to :lecture_session 
    belongs_to :test_session 
    belongs_to :question_session 
    belongs_to :student 

    def validate 
    raise "Question is not active!" unless question_session.active? 
    end 
end 

希望這會有所幫助。