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 } end
My Attachment model Factory was as follows:
# spec/factories/attachments.rb FactoryGirl.define do factory :attachment do item File.new(Rails.root + 'spec/factories/images/rails.png') end end And here is how I stubbed the successful upload: # spec/models/attachment_spec.rb require 'spec_helper' describe Attachment do before do Attachment.any_instance.stub(:save_attached_files).and_return(true) @attachment = FactoryGirl.create :attachment end describe "#your_method" do it "returns the correct results" do @attachment.your_method.should == :correct_result end end end
Have you used Paperclip? Have you figured out a better way to stub it? Please let me know in the comments!