Testing with attachment_fu

Manfred Stienstra, 26 Apr 2007, 10:56 in ruby on rails and testing, last updated 08 Jun 2007, 11:36 (edit).

When you’re testing uploads with attachment_fu, your files end up in RAILS_ROOT/public by default. This is not very handy because they might override your carefully uploaded bunny pictures in development. You can easily solve this by overriding the full_filename method on your attachment model. Let’s assume you have something like this.

class Asset < ActiveRecord::Base
  belongs_to :post  
  has_attachment :content_type => :image, :storage => :file_system
end

Then you can add the following to the file your tests are defined in:

class Asset
  def full_filename(thumbnail = nil)
    file_system_path = (thumbnail ? thumbnail_class : self).attachment_options[:path_prefix].to_s
    File.join(Dir::tmpdir(), file_system_path, *partitioned_path(thumbnail_name_for(thumbnail)))
  end
end

This will make your files get written to /tmp/public. If you have multiple tests that have to override the attachment class, it’s probably best to put it in a separate file.

Comments

  1. Jeffrey Hardy about 7 hours later: (delete)

    Nice tip. However, your best bet is to define the Asset class in test/mocks, which will save you having to litter your test files. Another thing to point out is that if you're using the S3 backend with a_fu, your amazon_s3 config can define a test environment wherein you can setup a bucket just for testing.

  2. Manfred Stienstra about 8 hours later: (delete)

    Defining it in mocks isn't going to work because the autoloader will load the mock instead of the actual model. That way you either have to re-define the entire model (yuk repeated code) or loose functionality.

  3. Jeffrey Hardy about 8 hours later: (delete)

    No, you just have to require the original model in the mock file. That way you're only overwriting the bits of the model you want to modify.

  4. Dick Davies 15 days later: (delete | show email)

    Just tried putting this in foo_controller_test.rb and you need an explicit "require 'model'" directly above it, or it blocks the 'main' definition of the model. (rails 1.2.3)

  5. Roger Classnifigure 43 days later: (delete)

    Found another good on how to hack on the plugin, can see the link on the topic here:

    <a href="http://www.dotrb.com/2007/6/9/attachment_fu-and-restful_authentication";>http://www.dotrb.com/2007/6/9/attachment_fu-and-restful_authentication<;/a>

    They go into some detail about how to override plugins in your model.

  6. Roger Classnifigure 43 days later: (delete)

  7. Michael Hartl 529 days later: (delete | show email)

    Thanks, this was very helpful.

Add your comment

In order to fight spam on this blog, posting comments from a browser without javascript is currently not supported.