Pat*_*hie 12 ruby xml integration-testing
给定一个控制器方法,如:
def show
@model = Model.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => model }
end
end
Run Code Online (Sandbox Code Playgroud)
编写集成测试以断言返回具有预期XML的最佳方法是什么?
小智 12
在集成测试中使用format和assert_select的组合效果很好:
class ProductsTest < ActionController::IntegrationTest
def test_contents_of_xml
get '/index/1.xml'
assert_select 'product name', /widget/
end
end
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请查看Rails文档中的assert_select.
小智 5
这是从控制器测试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
Run Code Online (Sandbox Code Playgroud)
ntalbott的答案显示了一个获取行动.后期行动有点棘手; 如果要将新对象作为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
Run Code Online (Sandbox Code Playgroud)
你可以在这里看到post的第二个参数不一定是参数哈希; 如果标题是正确的,它可以是一个字符串(包含XML).第三个论点是@headers,是我花了很多时间研究的部分.
(还要注意在比较assert_select中的整数值时使用to_s.)
| 归档时间: |
|
| 查看次数: |
4924 次 |
| 最近记录: |