如何为XML方法设置Rails集成测试?
时间:2020-03-05 18:52:26 来源:igfitidea点击:
给定一个控制器方法,例如:
def show @model = Model.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => model } end end
编写断言返回具有预期XML的集成测试的最佳方法是什么?
解决方案
回答
设置请求对象的接受标头:
@request.accept = 'text/xml' # or 'application/xml' I forget which
然后,我们可以断言响应主体等于我们期望的
assert_equal '<some>xml</some>', @response.body
回答
这是测试来自控制器的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
回答
在集成测试中结合使用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。
回答
这两个答案很不错,除了我的结果包括datetime字段外,在大多数情况下它们都是不同的,因此assert_equal
失败。看来我将需要使用XML解析器来处理include@ response.body
,然后比较各个字段,元素数量等。还是有一种更简单的方法?
回答
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
我们可以在此处看到要发布的第二个参数不必是参数哈希;如果标题正确,则它可以是字符串(包含XML)。第三个参数@headers是使我进行了大量研究才能弄清楚的部分。
(还要注意在assert_select中比较整数值时使用to_s。)