2011-10-17 151 views
9

我的控制器訪問上傳文件的tempfile屬性並將其傳遞給另一個模擬組件。我的測試代碼有在Rails 3.1控制器測試中模擬文件上傳

@file = mock(Object) 
    @file.stub_chain(:tempfile, :path).and_return('thefile.zip') 
    # ... 
    post :create, :file => @file 

和控制器代碼調用params[:file].tempfile.path

從滑軌升級3.0〜3.1後,將上述線開始使用

undefined method `tempfile' for "#[RSpec::Mocks::Mock:0x2b0d9a0 @name=Object]":String 

即失敗,Rails的3.1自動轉換params[:file]爲字符串。

當通過瀏覽器手動測試時,代碼正常工作。我試圖使用fixture_file_upload並且參數變成了File對象,但它沒有tempfile方法。

那麼如何將任意模擬對象作爲參數傳遞給Rails 3.1中的一個動作?

回答

14

終於找到this,它說明雖然fixture_file_upload返回的東西有一個@tempfile成員,但它缺少讀取器方法。解決如下

FileUtils.touch('file.zip') # fixture_file_upload needs the file to exist 
    @file = fixture_file_upload('file.zip') 
    class << @file 
    # The reader method is present in a real invocation, 
    # but missing from the fixture object for some reason (Rails 3.1.1) 
    attr_reader :tempfile 
    end 
0

我做了一個拉請求,來解決這個問題,請+1如果你喜歡它:https://github.com/brynary/rack-test/pull/67

+1

你拉似乎一直合併,但從Rails 3.2.13rc2開始,使用機架測試0.6.2,我還是不得不使用@ mpartel的解決方法,在 – SciPhi 2013-03-08 16:55:16

+0

之上獲得包含此修復的版本的任何機會? – sevenseacat 2013-06-19 08:09:58

3

我繞到這樣

upload_file = fixture_file_upload('files/stats_upload.csv', 'text/csv') 
upload_file.stubs(:tempfile).returns(upload_file)