【问题标题】:What is the Best Practice for testing api controllers(active model serializers)?测试 api 控制器(活动模型序列化程序)的最佳实践是什么?
【发布时间】:2016-01-28 20:47:18
【问题描述】:

我正在开发一个应用程序,到目前为止,我一直在测试诸如身份验证和请求响应代码之类的东西。但测试有效载荷的结构似乎是个好主意。 IE。如果有嵌入式资源或侧载资源。你们如何测试这个。这是我正在做的一些测试的示例。我正在使用活动模型序列化程序。但组织起来似乎有点麻烦。

describe '#index' do
  it 'should return an array of email templates' do
    template = EmailTemplate.new(name: 'new email template')
    EmailTemplate.stub(:all).and_return([template])
    get :index
    payload = {:email_templates => [JSON.parse(response.body)["email_templates"][0].symbolize_keys]}
    template_as_json_payload = {:email_templates => [ActiveModel::SerializableResource.new(template).as_json[:email_template] ]}
    expect(payload).to eq(template_as_json_payload)
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby testing rspec active-model-serializers


    【解决方案1】:

    我喜欢为 JSON 响应定义模式并验证测试中看到的任何响应是否符合它。仅此一项并不能保证响应的值是正确的,但它确实告诉您响应的结构符合您的期望。

    这些架构随后会成为客户端实现可以参考的 API 文档的一部分。通过在测试中使用模式,我更加确信 API 文档不会与实现不同步。为了通过测试而进行架构更改也是一个很好的提示,让我考虑更改对现有 API 客户端是否安全,或者我是否需要发布新的 API 版本。

    Thoughtbot 的人有一个使用 rspec 验证模式的好例子:https://robots.thoughtbot.com/validating-json-schemas-with-an-rspec-matcher

    【讨论】:

      【解决方案2】:

      这是一种方法:

      body = JSON.parse(response.body)
      assert_equal(body.keys, ["id", "author"])
      assert_equal(body["author"].keys, ["id", "name"])
      

      但您应该查看 Jonah 分享的链接,值得一读。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-16
        • 2011-06-28
        • 2014-03-09
        • 1970-01-01
        • 2019-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多