Rails JSON API 使用 JSON 中的 PARAMS 测试 POST 请求 [英] Rails JSON API testing POST request with PARAMS in JSON

查看:29
本文介绍了Rails JSON API 使用 JSON 中的 PARAMS 测试 POST 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个困扰我一段时间的问题.我正在构建一个 API 函数,它应该接收 json 中的数据和 json 中的响应.我的控制器测试运行良好(因为我抽象到那里的数据已经从 JSON 解码并且只需要解释答案).

This is a problem that has been bothering me for some time. I am building an API function that should receive data in json and response in json. My controller tests run fine(Since I abstract that the data gets there already decode from JSON and only the answer needs to be interpreted ).

我也知道该函数运行良好,因为我使用 curl 用 JSON 参数对其进行了测试,并且它运行良好.(例如: curl -i --header "Accept: application/json" --header "Content-Type: application/json" -d '{"test":{"email":"andreo@benjamin.dk"}}')

I Also know that the function runs fine since I have used curl to test it with JSON arguments and it works perfectly. (ex: curl -i --header "Accept: application/json" --header "Content-Type: application/json" -d '{"test":{"email":"andreo@benjamin.dk"}}' )

但显然我想编写请求(功能)测试来自动测试它,我认为它们应该像 curl 一样工作,即,像外部调用一样点击我的服务.这意味着我想在 JSON 中传递参数并接收答案.我很迷茫,因为我可以看到人们将参数视为已经解码的所有示例.

But obviously I would like to write request(feature) tests to test this automatically and the way I see it they should work exactly like curl, i.e., hit my service like it was an external call. That means that I would like to pass the arguments in JSON and receive an answer. I am pretty lost since all the examples I can see people treat arguments as it was already decoded.

我的问题是:我遵循了一个错误的前提,希望将参数和请求作为 JSON 发送,因为我将测试 rails 是否有效,因为这是它的责任?但我想看看我的代码对错误参数的鲁棒性,并想尝试使用 JSON.

My question is: I am following a wrong premise in wanting to send the arguments and request as a JSON one since i will be testing that rails works, because this is its responsibility? But I would like to see how robust my code his to wrong arguments and would like to try with JSON.

这种类型的东西:

it "should return an error if there is no correct email" do
    params = {:subscription => {:email => "andre"}}

    post "/magazine_subscriptions", { 'HTTP_ACCEPT' => "application/json", 'Content-Type' => 'application/json', 'RAW_POST_DATA' => params.to_json }
end

你知道这怎么可能吗?如果您认为我的测试有误,请告诉我.

Do you know how this is possible? and please let me know if you think I am testing it wrong.

一切顺利,

安德烈

推荐答案

我在此处的帖子中找到了答案(RSpec 请求测试在 POST JSON 参数中合并数组中的哈希),我认为我做错了与请求的参数有关.

I found my answer on a post here(RSpec request test merges hashes in array in POST JSON params), I think what I was doing wrong concerned the arguments to the request.

所以这有效:

it "should return an error if there is no correct email" do
    params = {:subscription => {:email => "andre"}}

    post "/magazine_subscriptions", params.to_json, {'ACCEPT' => "application/json", 'CONTENT_TYPE' => 'application/json'}
end

这篇关于Rails JSON API 使用 JSON 中的 PARAMS 测试 POST 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆