在Rails 3.1控制器测试中模拟文件上传

时间:2011-10-17 12:08:41

标签: file-upload mocking ruby-on-rails-3.1 rspec-rails

我的控制器访问上传文件的tempfile属性并将其传递给另一个模拟组件。我的测试代码有

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

,控制器代码调用params[:file].tempfile.path

从Rails 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中的动作?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

我绕过这条路

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

答案 2 :(得分:0)

我提出了解决此问题的拉取请求,如果您愿意,请+1:https://github.com/brynary/rack-test/pull/67