测试 api 控制器(活动模型序列化器)的最佳实践是什么?
What is the Best Practice for testing api controllers(active model serializers)?
我正在开发一个应用程序,到目前为止,我一直在测试身份验证和请求响应代码等内容。但测试有效载荷的结构似乎是个好主意。 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
我喜欢为 JSON 响应定义模式并验证测试中看到的任何响应都符合它。这本身并不能保证响应的值是正确的,但它确实告诉您响应的结构符合您的期望。
这些模式随后成为 API 文档的一部分,客户端实现可以参考这些文档。通过在测试中使用模式,我更加确信 API 文档不会与实现不同步。为了通过测试而进行架构更改也是一个很好的提示,让我考虑更改对现有 API 客户是否安全,或者我是否需要发布新的 API 版本。
Thoughtbot 的人们有一个使用 rspec 验证模式的很好的例子:https://robots.thoughtbot.com/validating-json-schemas-with-an-rspec-matcher
这是一种方法:
body = JSON.parse(response.body)
assert_equal(body.keys, ["id", "author"])
assert_equal(body["author"].keys, ["id", "name"])
但是你应该看看 Jonah 分享的 link,值得一读。
我正在开发一个应用程序,到目前为止,我一直在测试身份验证和请求响应代码等内容。但测试有效载荷的结构似乎是个好主意。 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
我喜欢为 JSON 响应定义模式并验证测试中看到的任何响应都符合它。这本身并不能保证响应的值是正确的,但它确实告诉您响应的结构符合您的期望。
这些模式随后成为 API 文档的一部分,客户端实现可以参考这些文档。通过在测试中使用模式,我更加确信 API 文档不会与实现不同步。为了通过测试而进行架构更改也是一个很好的提示,让我考虑更改对现有 API 客户是否安全,或者我是否需要发布新的 API 版本。
Thoughtbot 的人们有一个使用 rspec 验证模式的很好的例子:https://robots.thoughtbot.com/validating-json-schemas-with-an-rspec-matcher
这是一种方法:
body = JSON.parse(response.body)
assert_equal(body.keys, ["id", "author"])
assert_equal(body["author"].keys, ["id", "name"])
但是你应该看看 Jonah 分享的 link,值得一读。