如何制造具有 has_many 关联且可以在 rspec 中查询的对象?
How do you fabricate objects with has_many associations that can be queried in rspec?
我想在 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.
在这种情况下,您应该可以只使用 shorthand。
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
我想在 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.
在这种情况下,您应该可以只使用 shorthand。
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