2008-09-12 46 views
12

鑑於像一個控制器方法:如何爲XML方法設置Rails集成測試?

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

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

什麼是寫一個集成測試斷言返回了預期的XML的最佳方式?

回答

11

使用的格式和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

0

設置請求對象接受標頭:

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

然後你就可以斷言響應主體等於正是您期望

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

我知道那部分,找A..Z集成測試 – 2008-09-12 19:52:41

+1

這assert_equal也很脆弱。沒有元素或屬性順序的保證;如果它發生變化,你的測試將會中斷。文字字符串比較不是檢查XML樹相等的正確方法。 – bjnord 2010-08-20 15:14:05

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 
+0

這是一個功能測試,我已經有了。尋找一個集成測試。 – 2008-09-13 15:06:59

1

這兩個答案很好,除了我的結果包括datetime字段,它們在大多數情況下是不同的,所以assert_equal失敗。看起來我需要使用XML解析器處理include @response.body,然後比較各個字段,元素的數量等。或者有更簡單的方法嗎?

5

ntalbott的答案顯示一個獲取操作。帖子後面的動作有點棘手;如果要將新對象作爲XML消息發送,並使XML屬性顯示在控制器的參數哈希中,則必須正確獲取標題。下面是一個例子(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的。)

相關問題