RSPEC控制器规格,如何设置JSON主体和URL参数?

发布于 2025-01-29 09:44:07 字数 846 浏览 4 评论 0原文

body = { a: 1 }.to_json
params = { b: 2 }
post(:create, body: body, params: params, as: :json)

在控制器中,我有params [:a],但不是params [:b]

也许主体因为在控制器中解析的主体变为params,因此正在保留,但是在这种情况下,我还如何传递URL参数?

如果我删除as :: json,我会在params中看到URL参数,但由于MIME类型为text/html not 文本/JSON

Body是从固定装置加载的,必须按以下发送,因为车身已签名,因此无法与params,即params:json .parse(body).merge(params)

我可以解决这个问题:

request.query_string = "b=2"
post(:create, body: body, params: params, as: :json)

在这种情况下,我在params中同时获得了URL和身体参数,因此,当给出JSON主体和URL参数时,Rails Controller似乎做正确的事情。

body = { a: 1 }.to_json
params = { b: 2 }
post(:create, body: body, params: params, as: :json)

In the controller I have params[:a] but not params[:b]?

Maybe body is taking presidence since the parsed body becomes params in the controller, but in this case how do I also pass URL params?

If I remove as: :json I see the URL params in params but not the parsed JSON body as the MIME type is text/html not text/json.

The body is loaded from a fixture and must be sent as is because the body is signed, so it can't be merged with params, i.e. params: JSON.parse(body).merge(params).

I can hack around this problem as such:

request.query_string = "b=2"
post(:create, body: body, params: params, as: :json)

In this case I get both the URL and body params in params, so it seems the Rails controller does the right thing when given both a JSON body and URL params.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情痴 2025-02-05 09:44:07

如果我们这样更改路线:

post '/foo?a=:a', to: 'foos#create'

我们最终都会以params中的定义URL参数和身体参数。

If we change the routes as such:

post '/foo?a=:a', to: 'foos#create'

we do end up with both the defined URL params and body params in params.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文