2009-10-01 66 views
3

有沒有一種標準或最佳實踐的方式來測試rails中的動作是否返回正確的文本?例如,我有一個是用來做AJAX驗證,做以下簡單的動作:如何斷言操作返回正確的文本?

def get_object_id 
    if params[:id].blank? 
    return render(:text => -1, :layout => false) 
    end 

    my_object = MyObject.find_by_id(params[:id].strip) 

    # If the object is valid return the object id 
    if my_object and my_object.active? 
    return render(:text => my_object.id, :layout => false) 
    end 

    # Otherwise, return -1 
    return render(:text => -1, :layout => false) 
end 

現在,我使用的是@應答對象在我的測試...即:

def test_get_object_id_returns_invalid_for_non_existent_id 
    # Act 
    get :get_object_id, :id => 999 

    # Assert 
    assert_response :success 
    assert_equal "-1", @response.body 
end 

但是,雖然大多數人都是新手,但我迄今爲止所看到的似乎表明,除了檢查@request.body之外,可能還有更好的方法來執行此操作。

所以,我給你的紅寶石專家的問題是:這是最好的方式嗎?

回答

3

我覺得你的位置已經。

assert_select只適用於XML內容,所以對於其他格式您必須自行打印。如果我正在做很多這些,我可能會添加一個名爲斷言方法ActionController::TestCase

例如

def assert_response_equals(v) 
    assert_equal v.to_s, @response.body, "Expected response body to be #{v.inspect}" 
end 

這將允許您跳過引號。

+0

這是個好主意。你的意思是ActionController :: TestCase而不是ActionController :: TestClass?我似乎無法找到關於後者的任何文件。 – jerhinesmith 2009-10-01 19:19:30

+0

糟糕,糾正。 – cwninja 2009-10-01 20:04:54