【问题标题】:How to setup a Rails integration test for XML methods?如何为 XML 方法设置 Rails 集成测试?
【发布时间】:2008-09-12 18:11:42
【问题描述】:

给定一个控制器方法,例如:

def show
  @model = Model.find(params[:id])

  respond_to do |format|
    format.html # show.html.erb
    format.xml  { render :xml => model }
  end
end

编写断言返回具有预期 XML 的集成测试的最佳方法是什么?

【问题讨论】:

    标签: xml ruby integration-testing


    【解决方案1】:

    在集成测试中结合使用 format 和 assert_select 效果很好:

    class ProductsTest < ActionController::IntegrationTest
      def test_contents_of_xml
        get '/index/1.xml'
        assert_select 'product name', /widget/
      end
    end
    

    有关详细信息,请查看 Rails 文档中的 assert_select

    【讨论】:

      【解决方案2】:

      ntalbott 的回答显示了一个 get 操作。发布动作有点棘手;如果您想将新对象作为 XML 消息发送,并让 XML 属性显示在控制器的 params 哈希中,则必须正确设置标题。这是一个示例(Rails 2.3.x):

      class TruckTest < ActionController::IntegrationTest
        def test_new_truck
          paint_color = 'blue'
          fuzzy_dice_count = 2
          truck = Truck.new({:paint_color => paint_color, :fuzzy_dice_count => fuzzy_dice_count})
          @headers ||= {}
          @headers['HTTP_ACCEPT'] = @headers['CONTENT_TYPE'] = 'application/xml'
          post '/trucks.xml', truck.to_xml, @headers
          #puts @response.body
          assert_select 'truck>paint_color', paint_color
          assert_select 'truck>fuzzy_dice_count', fuzzy_dice_count.to_s
        end
      end
      

      您可以在这里看到 post 的第二个参数不必是参数哈希;它可以是一个字符串(包含 XML),if 标题是正确的。第三个论点 @headers 是我经过大量研究才弄明白的部分。

      (注意在 assert_select 中比较整数值时使用 to_s。)

      【讨论】:

        【解决方案3】:

        这是测试来自控制器的 xml 响应的惯用方式。

        class ProductsControllerTest < ActionController::TestCase
          def test_should_get_index_formatted_for_xml
            @request.env['HTTP_ACCEPT'] = 'application/xml'
            get :index
            assert_response :success
          end
        end
        

        【讨论】:

        • 这是一个功能测试,我已经有了。正在寻找集成测试。
        【解决方案4】:

        这 2 个答案很好,除了我的结果包括日期时间字段,在大多数情况下这些字段会有所不同,因此 assert_equal 失败。看来我需要使用 XML 解析器处理包含 @response.body,然后比较各个字段、元素数量等。或者有更简单的方法吗?

        【讨论】:

        • 是的;日期和时间字段是 assert_equal 是比较 XML 树的错误方法的另一个原因。就我自己而言,我没有在测试中比较整个对象的相等性;我已经使用了 assert_select(如上面的 ntalbott 所示)来检查我想要检查的特定属性。
        【解决方案5】:

        设置请求对象接受头:

        @request.accept = 'text/xml' # or 'application/xml' I forget which
        

        然后您可以断言响应正文等于您的预期

        assert_equal '<some>xml</some>', @response.body
        

        【讨论】:

        • 我知道的那部分,正在寻找 A..Z 集成测试
        • 那个 assert_equal 也很脆弱。不保证元素或属性的顺序;如果它改变了,你的测试就会中断。文字字符串比较不是检查 XML 树是否相等的正确方法。
        猜你喜欢
        • 2012-12-09
        • 2021-04-13
        • 1970-01-01
        • 1970-01-01
        • 2012-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-24
        相关资源
        最近更新 更多