Rails JSON API使用JSON中的PARAMS测试POST请求

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

我也知道该函数运行正常,因为我使用curl测试它与JSON参数,它完美地工作。 (例如:curl -i –header“Accept:application / json”–header“Content-Type:application / json”-d'{“test”:{“email”:“andreo@benjamin.dk”}} ‘)

但显然我想编写请求(function)测试来自动测试这个,我看到它应该像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 

你知道这有可能吗? 如果您认为我测试错了,请告诉我。

祝一切顺利,

安德烈

我在这里的post上找到了我的答案( RSpec请求测试在POST JSON参数中合并哈希数组中的哈希 ),我认为我做错了涉及请求的参数。

所以这工作:

 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 
 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