Using Shoulda to test Paperclip’s validates_attachment_file_name and validates_attachment_content_type

Using Shoulda

The simplest way to test validates_attachment_file_name and validates_attachment_content_type configurations of the Rails model that has a paperclip attachment is to use the allow_value method in the shoulda gem.

The following example uses rspec to demonstrate. First, we generate our model

rails g model PdfUpload

We add a paperclip attachment as part of the document:

class CreatePdfUploads < ActiveRecord::Migration
  def change
    create_table :pdf_uploads do |t|
      t.attachment :document
      t.timestamps
    end
  end
end

Run the migration:

rake db:migrate

Next, we add the validations to our model:

class PdfUpload < ActiveRecord::Base
  has_attached_file :document
  validates_attachment_presence :document
  validates_attachment_file_name :document, matches: %r{\.pdf\Z}i
  validates_attachment_content_type :document, content_type: "application/pdf"
end

Note that we use the \Z to indicate end of line instead $.

Finally, we add an rspec spec to verify that this validation is in place:

describe PdfUpload do

  describe "validations" do
    context "validate document file name ends with 'pdf'" do
      it { should allow_value("foo.pdf").for(:document_file_name) }
      it { should allow_value("foo.PDF").for(:document_file_name) }
      it { should_not allow_value("bar.doc").for(:document_file_name) }
      it { should_not allow_value("bar.txt").for(:document_file_name) }
    end
  end

end

Run the spec:

bundle exec rspec spec/models/pdf_upload_spec.rb