【问题标题】:Generate JSON with associations for API testing (Rails, Rspec, FactoryGirl)生成带有 API 测试关联的 JSON(Rails、Rspec、FactoryGirl)
【发布时间】:2013-08-13 15:43:00
【问题描述】:

我是 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?

谢谢。

【问题讨论】:

  • 您介意指向您提到的有关自定义 JSON 策略的 FactoryGirl 文档吗?
  • 更新的问题与文档链接

标签: ruby-on-rails factory-bot ruby-on-rails-4 rspec2 rspec-rails


【解决方案1】:

您可以使用FactoryGirlJsonActiveModelSerializer 来生成复合JSON

API 数据中的嵌套关​​联很糟糕——随着复杂性的增加,层次结构将变得非规范化和脆弱。请参阅:JSON API 中的 Compound Documents(又名 sideloading)。 ActiveModelSerializer 可以轻松生成复合文档

FactoryGirlJson 是一个非常新的项目,我现在才自己尝试。我发现在将 FactoryGirlJson 添加到 Gemfile 之前升级到 FactoryGirlRails >= 4.2 可以解决旧版本 FactoryGirlJson 的一些心痛。

【讨论】:

    猜你喜欢
    • 2013-03-21
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多