我是 Rails (4.0.0) 和 FactoryGirl (4.2.0) 的新手,我正在尝试为 POST 生成 JSON。我正在使用 FactoryGirl 文档(https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#custom-strategies)中建议的自定义策略。
class JsonStrategy
def initialize
@strategy = FactoryGirl.strategy_by_name(:create).new
end
delegate :association, to: :@strategy
def result(evaluation)
@strategy.result(evaluation).to_json
end
end
我的问题是我希望 JSON 返回一个指定的关联。
假设我有两节课
class Votes
belongs_to :people
end
class Person
has_many :votes
end
使用 FactoryGirl 能够执行以下操作会很不错:
json = json(:person, :include => [:votes])
我希望我的 JSON 对象返回如下内容:
{
'first_name': 'John',
'last_name': 'Doe',
'votes' : [
{
'name': 'Vote 1',
'yea': false
},
{
'name': 'Vote 2',
'yea': true
}
]
}
FactoryGirl 可以做到这一点吗?如果没有,是否有更好的方法来使用 Rspec (2.14.1) 测试 JSON API?
谢谢。