我有以下对象和关系,
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因此,很明显,问题模型的状态现在与测试和类的状态相耦合。
在创建单元测试时,为了测试这一点,我需要设置所有这些状态,这会变得相当笨拙,特别是在业务案例变得越来越复杂的情况下。
我怎样才能避免这种情况?
发布于 2012-02-20 13:07:10
我不熟悉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希望这能有所帮助。
https://stackoverflow.com/questions/9313982
复制相似问题