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

mpa*_*tel 9 file-upload mocking rspec-rails ruby-on-rails-3.1

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

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

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

从Rails 3.0升级到3.1后,上面的行开始失败了

undefined method `tempfile' for "#[RSpec::Mocks::Mock:0x2b0d9a0 @name=Object]":String
Run Code Online (Sandbox Code Playgroud)

也就是说,Rails 3.1 params[:file]自动转换为字符串.

通过浏览器手动测试时,代码可以正常工作.我试图使用fixture_file_upload,参数成为一个File对象,但它没有tempfile方法.

那么如何将任意模拟对象作为参数传递给Rails 3.1中的动作?

mpa*_*tel 14

终于找到了这个,它告诉我虽然返回的东西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
Run Code Online (Sandbox Code Playgroud)