【问题标题】:Functional testing of a JSON Rails APIJSON Rails API 的功能测试
【发布时间】:2013-12-02 11:51:23
【问题描述】:

我目前正在构建一个由 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", "controller"=>"posts", "action"=>"update", "format"=>"json"}
    
  • JSON 格式,但不包含在参数中

    test 'passing JSON' do
      patch :update, { key: "value" }.to_json
    end
    
    # Raw Post: "{\"key\":\"value\"}"
    # Params: {"controller"=>"posts", "action"=>"update"}
    
  • JSON 格式,但不包含在参数中

    test 'passing JSON, setting format' do
      patch :update, { key: "value" }.to_json, format: :json
    end
    
    # Raw Post: "{\"key\":\"value\"}"
    # Params: {"format"=>"json", "controller"=>"posts", "action"=>"update"}
    

这个列表更长,我只是想告诉你我的问题。我也测试了将AcceptContent-Type 标头设置为application/json,似乎没有任何帮助。我做错了什么,或者这是 Rails 功能测试中的错误?

【问题讨论】:

    标签: ruby-on-rails json ruby-on-rails-4 functional-testing rails-api


    【解决方案1】:

    这是a bug,由该问题的同一作者报告。它不太可能在 Rails 5 之前得到修复,或者通过查看它被分配到的里程碑似乎是这样。

    如果你像我一样来到这里,在处理这个问题几个小时后却不知道它确实是一个错误,也许你想知道你可以在集成测试中做到这一点:

    $ 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
    

    【讨论】:

    • 我会将其标记为答案,因为它是解决此问题的最佳方法。经验教训:根本不要使用功能测试,进行完整的集成测试。
    • 这是如何在 Rails 6 中完成的?测试文档没有给出示例。
    猜你喜欢
    • 2012-05-30
    • 2014-12-02
    • 1970-01-01
    • 2015-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多