2014-09-06 14 views
0

字符串我有以下代碼來測試文件上傳:的Rails 3 TestUnit文件夾具將它視爲成爲控制器

test 'when a user adds an attachment to an existing candidate, the attachment shows up on the candidates page' do 
    user = login_user 
    opportunity = opportunities(:with_candidates) 
    candidate = candidates(:first) 
    upload = fixture_file_upload(ActionController::TestCase.fixture_path + 'files/file_upload_support_image.jpeg', 'image/jpeg') 
    attributes = { attachments: [upload] } 

    user.put opportunity_candidate_path(opportunity, candidate, request: attributes) 
    user.follow_redirect! 

    assert_match /#{upload.original_filename}/, fixer.response.body, 'The filename of the attachment should appear on the opportunity candidates page' 
end 

測試失敗,因爲該文件沒有得到重視。

該代碼在瀏覽器中運行時發生作用 - 事實證明我錯誤地寫了assert並且得到了錯誤的傳球。現在assert是正確的,測試失敗。

調試時,我發現測試中的upload變量與#<Rack::Test::UploadedFile:0x007f85ca141c50>類似。但是,當我調試控制器時,params散列中的值是"#<Rack::Test::UploadedFile:0x007f85ca141c50>"

請注意引號。 Rails已將文件上傳轉換爲字符串!

由於測試和控制器之間沒有我的代碼,並且在瀏覽器中運行該應用程序時有效,所以我猜測我在測試中如何構造params散列或tempfile本身可能是錯誤的。

任何想法我做錯了什麼?

回答

0

好的,原來我在測試中做了一些不正確的事情。但是,如果您傳遞最常見類型的參數,則不會顯示此錯誤,因此找到它可能有點棘手!

user.put opportunity_candidate_path(opportunity, candidate, request: attributes) 

應該

user.put opportunity_candidate_path(opportunity, candidate), request: attributes 

注意移動括號。 D'哦!

這個可能不容易發現的原因是..._path方法中的未知鍵爲仍然作爲參數傳遞。但是,它們被解析爲已被編碼到URL查詢字符串中,如GET請求。

對於傳遞文本值和整數外鍵作爲參數的常見情況,這種修改並不妨礙任何工作,只是對於更復雜的對象纔會成爲問題。

相關問題