ruby-on-rails – JSON Rails API的功能测试
发布时间:2020-12-16 23:09:23 所属栏目:百科 来源:网络整理
导读:我目前正在构建一个由Rails / rails-api支持的 JSON API.我有一个路由接受通过PATCH请求发送的JSON和一个需要访问原始请求/ JSON的过滤器. 出于测试目的,我在过滤前添加了以下内容以显示我的问题 before_filter do puts "Raw Post: #{request.raw_post.inspe
我目前正在构建一个由Rails / rails-api支持的
JSON API.我有一个路由接受通过PATCH请求发送的JSON和一个需要访问原始请求/ JSON的过滤器.
出于测试目的,我在过滤前添加了以下内容以显示我的问题 before_filter do puts "Raw Post: #{request.raw_post.inspect}" puts "Params: #{params.inspect}" end 以下curl请求按预期工作: curl -X PATCH -H "Content-Type: application/json" -d '{"key":"value"}' http://localhost:3000/update # Raw Post: "{"key":"value"}" # Params: {"key"=>"value","action"=>"update","controller"=>"posts"} 但是,我无法测试此方法,以下调用都不起作用: >包括参数,但不是JSON转移 test 'passing hash' do patch :update,{ key: "value" } end # Raw Post: "key=value" # Params: {"key"=>"value","controller"=>"posts","action"=>"update"} >包括参数,但同样不是JSON转移 test 'passing hash,setting the format' do patch :update,{ key: "value" },format: :json end # Raw Post: "key=value" # Params: {"key"=>"value","format"=>"json"} > JSON格式,但不包括在params中 test 'passing JSON' do patch :update,{ key: "value" }.to_json end # Raw Post: "{"key":"value"}" # Params: {"controller"=>"posts","action"=>"update"} > JSON格式,但不包括在params中 test 'passing JSON,setting format' do patch :update,{ key: "value" }.to_json,format: :json end # Raw Post: "{"key":"value"}" # Params: {"format"=>"json","action"=>"update"} 这个列表甚至更长,我只想告诉你我的问题.我测试了将Accept和Content-Type标头都设置为application / json,似乎没有任何帮助.我做错了什么,或者这是Rails功能测试中的错误? 解决方法
这是
a bug,由该问题的同一作者报道.它不可能在Rails 5之前修复,或者通过查看它已分配给它的里程碑似乎是这样.
如果你像我一样降落在这里,经过几个小时处理这个问题,不知道它真的是一个bug,也许你想知道你可以在集成测试中做到这一点: $rails g integration_test my_integration_test require 'test_helper' class MyIntegrationTestTest < ActionDispatch::IntegrationTest setup do @owner = Owner.create(name: 'My name') @json = { name: 'name',value: 'My new name' }.to_json end test "update owner passing json" do patch "/owners/#{@owner.id}",@json,{ 'Accept' => Mime::JSON,'Content-Type' => Mime::JSON.to_s} assert_response :success assert_equal 'application/json',response.headers['Content-Type'] assert_not_nil assigns :owner assert_equal 'My new name',assigns(:owner).name end end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |