2011-10-17 73 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)