How To Stub Paperclip’s has_attached_file Method With RSpec

In the past few weeks, I’ve been working with Paperclip, an incredible rails gem for uploading files to Amazon’s S3. However, it took me some substantial time to figure out how to write rspec tests for Paperclip’s has_attached_file method, which I used in my model. Here is how I did it…

First, here is part of my Attachment model, which I use for uploading files related to each product:

# app/models/attachment.rb 
class Attachment < ActiveRecord::Base
  require 'open-uri'
  attr_accessible :item

  belongs_to :product

  has_attached_file :item,
                    storage: :s3,
                    s3_credentials: { :bucket => ENV['AWS_BUCKET'],
                                      :access_key_id => ENV['AWS_ACCESS_KEY_ID'],
                                      :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
                    s3_permissions: :private,
                    path: "attachments/:id"

  validates_attachment :item, presence: true, size: { less_than: 10.megabytes }


My Attachment model Factory was as follows:

# spec/factories/attachments.rb 
FactoryGirl.define do 
  factory :attachment do 
    item + 'spec/factories/images/rails.png') 
And here is how I stubbed the successful upload:

# spec/models/attachment_spec.rb 
require 'spec_helper' 
describe Attachment do 
  before do 
    @attachment = FactoryGirl.create :attachment 
  describe "#your_method" do 
   it "returns the correct results" do 
    @attachment.your_method.should == :correct_result end 

Have you used Paperclip? Have you figured out a better way to stub it? Please let me know in the comments!

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.