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

很明显,问题模型的状态现在与测试和课堂的状态相耦合。

在创建单元测试时,为了测试它,我需要设置所有这些状态,这变得非常笨拙,尤其是当业务案例变得越来越复杂时。

我怎样才能避免这种情况?

4

1 回答 1

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

希望这可以帮助。

于 2012-02-20T05:07:10.493 回答