代码之家  ›  专栏  ›  技术社区  ›  Patrick Ritchie

如何为XML方法设置Rails集成测试?

  •  12
  • Patrick Ritchie  · 技术社区  · 18 年前

    def show
      @model = Model.find(params[:id])
    
      respond_to do |format|
        format.html # show.html.erb
        format.xml  { render :xml => model }
      end
    end
    

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

    5 回复  |  直到 13 年前
        1
  •  12
  •   Faisal Feroz    18 年前

    在集成测试中结合使用format和assert_select非常有效:

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

    有关更多详细信息,请查看 assert_select 在Rails文档中。

        2
  •  5
  •   bjnord    16 年前

    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
    

    如果 标题是正确的。第三个参数@headers是我花了大量研究才弄明白的部分。

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

        3
  •  5
  •   Community Mohan Dere    12 年前

    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
  •  1
  •   Danilo Cândido Rewar    8 年前

    这两个答案都很好,只是我的结果包括datetime字段,这在大多数情况下是不同的,所以 assert_equal 失败。看来我需要处理include @response.body

        5
  •  0
  •   Michael Sepcot    18 年前

    设置请求对象接受标头:

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

    然后,您可以断言响应主体与您期望的内容相同

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