给予控制方法,如:

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

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

什么是最好的方式编写一个一体化试验的断言,返回的具有预期的XML?

有帮助吗?

解决方案

结合使用的格式和assert_select在一个一体化试验的伟大工程:

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

欲了解更多详情请查看 assert_select 在铁轨上文档。

其他提示

答案从ntalbott示出获取的行动。后行动是有点棘手;如果你想发送的新的对象为XML消息,并有XML特性出现在params散列在控制器,你有得到标题的权利。这里有一个例子(轨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

你可以在这里看到的第2个参数后没有成为一个参数的散列;它可以是一个串(含XML), 如果 标题是正确的。3参数,@头,是的一部分,我花了很多研究,以弄清楚。

(还请注意使用to_s在比较整数值在assert_select.)

这是惯用方式的试验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

这些2的答案是好的,除了我的结果包括的日期时间的领域,其功能不同,在大多数情况下,这样的 assert_equal 失败。它的出现,我会需要处理包括 @response.body 使用XML parser,然后进行比较各个领域的元素数量,等等。或是有一个更简单的方法?

设置请求对象的接受标题:

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

然后你可以断言的反应体等于什么你期待

assert_equal '<some>xml</some>', @response.body
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top