Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking file uploads in Rails 3.1 controller tests

My controller accesses the tempfile attribute of an uploaded file and passes it to another mocked component. My test code has

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

and the controller code calls params[:file].tempfile.path.

After upgrading from Rails 3.0 to 3.1, the above line started failing with

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

That is, Rails 3.1 converted params[:file] to a string automatically.

The code works properly when tested manually through a browser. I tried to use fixture_file_upload and the parameter became a File object but it had no tempfile method.

So how do I pass an arbitrary mock object as a parameter to an action in Rails 3.1?

like image 854
mpartel Avatar asked Oct 17 '11 12:10

mpartel


1 Answers

Finally found this, which tells that although the thing returned by fixture_file_upload has a @tempfile member, it lacks the reader method. Solved as follows

  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
like image 127
mpartel Avatar answered Sep 21 '22 05:09

mpartel