如何使用可在rspec中查询的has_many关联来构造对象?

时间:2019-03-07 04:24:53

标签: ruby-on-rails rspec fabrication-gem

我有要在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。

1 个答案:

答案 0 :(得分: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