在Rails 3.1控制器测试中模拟文件上传
问题描述:
我的控制器访问上传文件的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中的一个动作?
答
终于找到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
答
我绕到这样
upload_file = fixture_file_upload('files/stats_upload.csv', 'text/csv')
upload_file.stubs(:tempfile).returns(upload_file)
你拉似乎一直合并,但从Rails 3.2.13rc2开始,使用机架测试0.6.2,我还是不得不使用@ mpartel的解决方法,在 – SciPhi 2013-03-08 16:55:16
之上获得包含此修复的版本的任何机会? – sevenseacat 2013-06-19 08:09:58