0

我有这个模式,我想在 rspec 中测试。

class Question
  has_many :choices
end

class Choice
  belongs_to :question
  validates_presence_of :question
end

这似乎不起作用:

Fabricator(:question) do
  text { sequence(:text) { |i| "my question#{i}" } }
  choices(count: 2) { Fabricate(:choice, question: question)}
end

也不是这个:

Fabricator(:question) do
  text { sequence(:text) { |i| "my question#{i}" } }

  before_save do |question|
    choices(count: 2) { Fabricate(:choice, question: question)}
  end
end

我遇到的问题是,如果我像这样构建制造:

Fabricator(:question) do 
  text "question"
end
question = Fabricate(:question)
choice_a = Fabricate(:choice, question: question)
choice_b = Fabricate(:choice, question: question)
(question.choices == nil)  #this is true

在我的 rspec 中,我需要查询 question.choices。

4

1 回答 1

1

在这种情况下,您应该可以只使用速记。

Fabricator(:question) do
  choices(count: 2)
end

Fabrication 将自动构建正确的关联树,并让 ActiveRecord 在后台执行其操作以将它们关联到数据库中。您从该调用返回的对象应该是完全持久化和可查询的。

如果您需要覆盖选择中的值,您可以这样做。

Fabricator(:question) do
  choices(count: 2) do
    # Specify a nil question here because ActiveRecord will fill it in for you when it saves the whole tree.
    Fabricate(:choice, question: nil, text: 'some alternate text')
  end
end
于 2019-03-07T14:52:58.660 回答