Ruby on rails Rails JSON API使用JSON中的参数测试POST请求

Ruby on rails Rails JSON API使用JSON中的参数测试POST请求,ruby-on-rails,json,api,testing,rspec,Ruby On Rails,Json,Api,Testing,Rspec,这是一个困扰我一段时间的问题。我正在构建一个API函数,该函数应该以json格式接收数据,并以json格式响应。我的控制器测试运行得很好(因为我提取到的数据已经从JSON解码了,只需要解释答案) 我还知道该函数运行良好,因为我使用curl用JSON参数对其进行了测试,它工作得非常好。 (例如:curl-i--header“Accept:application/json”-header“Content Type:application/json”-d'{“test”:{“email”:”andre

这是一个困扰我一段时间的问题。我正在构建一个API函数,该函数应该以json格式接收数据,并以json格式响应。我的控制器测试运行得很好(因为我提取到的数据已经从JSON解码了,只需要解释答案)

我还知道该函数运行良好,因为我使用curl用JSON参数对其进行了测试,它工作得非常好。 (例如:curl-i--header“Accept:application/json”-header“Content Type:application/json”-d'{“test”:{“email”:”andreo@benjamin.dk“}}')

但显然,我想编写请求(特性)测试来自动测试这一点,我认为它们应该像curl一样工作,也就是说,像外部调用一样点击我的服务。这意味着我希望以JSON格式传递参数并接收答案。我很迷茫,因为我能看到的所有例子都是人们对待论点的方式,因为它已经被解码了

我的问题是:我想要以JSON的形式发送参数和请求,这是错误的前提,因为我将测试rails是否工作,因为这是它的责任?但我希望看到我的代码对错误参数的鲁棒性,并希望尝试使用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
你知道这怎么可能吗?如果你认为我测试错了,请告诉我

祝你一切顺利


Andre

我在这里的一篇帖子上找到了我的答案(),我认为我做错了与请求相关的论点

因此,这起了作用:

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

为简洁起见,请将其写成
post'/magazine\u subscriptions',params.to\u json,format::json
@user664833。我不认为这更优雅。如果您已经将其格式化为json对象,则必须使用to\u json。我认为应该是
post'/magazine_subscriptions',params,format::json
post”/magazine_subscriptions.json',params
谢谢。我很难找到rails最新版本的例子<代码>发布“/杂志订阅”,订阅:订阅参数,格式::json是我的关键。无需对json执行
describe '#create' do 
  let(:email) {'andre'}
  let(:attrs) {{email: email}}
  let(:params) {{format: :json, subscription: attrs}}

  it "should return an error if there is no correct email" do
    post "/magazine_subscriptions", params
  end
end